blob: 974a4a22218fd5689cb4720981ecb5e6c080298c [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
Antoine Pitrou921e9432017-11-07 17:23:29 +010020from . import constants
Andrew Svetlovf74ef452017-12-15 07:04:38 +020021from . import format_helpers
Antoine Pitrou921e9432017-11-07 17:23:29 +010022
23
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070024class Handle:
25 """Object returned by callback registration methods."""
26
Victor Stinner80f53aa2014-06-27 13:52:20 +020027 __slots__ = ('_callback', '_args', '_cancelled', '_loop',
Victor Stinner1b38bc62014-09-17 23:24:13 +020028 '_source_traceback', '_repr', '__weakref__')
Yury Selivanovb1317782014-02-12 17:01:52 -050029
Yury Selivanov569efa22014-02-18 18:02:19 -050030 def __init__(self, callback, args, loop):
Yury Selivanov569efa22014-02-18 18:02:19 -050031 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070032 self._callback = callback
33 self._args = args
34 self._cancelled = False
Victor Stinner1b38bc62014-09-17 23:24:13 +020035 self._repr = None
Victor Stinner80f53aa2014-06-27 13:52:20 +020036 if self._loop.get_debug():
Andrew Svetlovf74ef452017-12-15 07:04:38 +020037 self._source_traceback = format_helpers.extract_stack(
38 sys._getframe(1))
Victor Stinner80f53aa2014-06-27 13:52:20 +020039 else:
40 self._source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070041
Victor Stinner1b38bc62014-09-17 23:24:13 +020042 def _repr_info(self):
Victor Stinnerf68bd882014-07-10 22:32:58 +020043 info = [self.__class__.__name__]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070044 if self._cancelled:
Victor Stinner975735f2014-06-25 21:41:58 +020045 info.append('cancelled')
Victor Stinnerf68bd882014-07-10 22:32:58 +020046 if self._callback is not None:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020047 info.append(format_helpers._format_callback_source(
48 self._callback, self._args))
Victor Stinnerf68bd882014-07-10 22:32:58 +020049 if self._source_traceback:
50 frame = self._source_traceback[-1]
Yury Selivanov6370f342017-12-10 18:36:12 -050051 info.append(f'created at {frame[0]}:{frame[1]}')
Victor Stinner1b38bc62014-09-17 23:24:13 +020052 return info
53
54 def __repr__(self):
55 if self._repr is not None:
56 return self._repr
57 info = self._repr_info()
Yury Selivanov6370f342017-12-10 18:36:12 -050058 return '<{}>'.format(' '.join(info))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070059
60 def cancel(self):
Yury Selivanov592ada92014-09-25 12:07:56 -040061 if not self._cancelled:
62 self._cancelled = True
63 if self._loop.get_debug():
64 # Keep a representation in debug mode to keep callback and
65 # parameters. For example, to log the warning
66 # "Executing <Handle...> took 2.5 second"
67 self._repr = repr(self)
68 self._callback = None
69 self._args = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070070
Marat Sharafutdinov69cfed12017-11-07 12:06:05 +030071 def cancelled(self):
72 return self._cancelled
73
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070074 def _run(self):
75 try:
76 self._callback(*self._args)
Yury Selivanov569efa22014-02-18 18:02:19 -050077 except Exception as exc:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020078 cb = format_helpers._format_callback_source(
79 self._callback, self._args)
Yury Selivanov6370f342017-12-10 18:36:12 -050080 msg = f'Exception in callback {cb}'
Victor Stinner80f53aa2014-06-27 13:52:20 +020081 context = {
Yury Selivanov569efa22014-02-18 18:02:19 -050082 'message': msg,
83 'exception': exc,
84 'handle': self,
Victor Stinner80f53aa2014-06-27 13:52:20 +020085 }
86 if self._source_traceback:
87 context['source_traceback'] = self._source_traceback
88 self._loop.call_exception_handler(context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070089 self = None # Needed to break cycles when an exception occurs.
90
91
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070092class TimerHandle(Handle):
93 """Object returned by timed callback registration methods."""
94
Yury Selivanov592ada92014-09-25 12:07:56 -040095 __slots__ = ['_scheduled', '_when']
Yury Selivanovb1317782014-02-12 17:01:52 -050096
Yury Selivanov569efa22014-02-18 18:02:19 -050097 def __init__(self, when, callback, args, loop):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070098 assert when is not None
Yury Selivanov569efa22014-02-18 18:02:19 -050099 super().__init__(callback, args, loop)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200100 if self._source_traceback:
101 del self._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700102 self._when = when
Yury Selivanov592ada92014-09-25 12:07:56 -0400103 self._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700104
Victor Stinner1b38bc62014-09-17 23:24:13 +0200105 def _repr_info(self):
106 info = super()._repr_info()
107 pos = 2 if self._cancelled else 1
Yury Selivanov6370f342017-12-10 18:36:12 -0500108 info.insert(pos, f'when={self._when}')
Victor Stinner1b38bc62014-09-17 23:24:13 +0200109 return info
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700110
111 def __hash__(self):
112 return hash(self._when)
113
114 def __lt__(self, other):
115 return self._when < other._when
116
117 def __le__(self, other):
118 if self._when < other._when:
119 return True
120 return self.__eq__(other)
121
122 def __gt__(self, other):
123 return self._when > other._when
124
125 def __ge__(self, other):
126 if self._when > other._when:
127 return True
128 return self.__eq__(other)
129
130 def __eq__(self, other):
131 if isinstance(other, TimerHandle):
132 return (self._when == other._when and
133 self._callback == other._callback and
134 self._args == other._args and
135 self._cancelled == other._cancelled)
136 return NotImplemented
137
138 def __ne__(self, other):
139 equal = self.__eq__(other)
140 return NotImplemented if equal is NotImplemented else not equal
141
Yury Selivanov592ada92014-09-25 12:07:56 -0400142 def cancel(self):
143 if not self._cancelled:
144 self._loop._timer_handle_cancelled(self)
145 super().cancel()
146
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700147
148class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100149 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700150
151 def close(self):
152 """Stop serving. This leaves existing connections open."""
153 return NotImplemented
154
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200155 async def wait_closed(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700156 """Coroutine to wait until service is closed."""
157 return NotImplemented
158
159
160class AbstractEventLoop:
161 """Abstract event loop."""
162
163 # Running and stopping the event loop.
164
165 def run_forever(self):
166 """Run the event loop until stop() is called."""
167 raise NotImplementedError
168
169 def run_until_complete(self, future):
170 """Run the event loop until a Future is done.
171
172 Return the Future's result, or raise its exception.
173 """
174 raise NotImplementedError
175
176 def stop(self):
177 """Stop the event loop as soon as reasonable.
178
179 Exactly how soon that is may depend on the implementation, but
180 no more I/O callbacks should be scheduled.
181 """
182 raise NotImplementedError
183
184 def is_running(self):
185 """Return whether the event loop is currently running."""
186 raise NotImplementedError
187
Victor Stinner896a25a2014-07-08 11:29:25 +0200188 def is_closed(self):
189 """Returns True if the event loop was closed."""
190 raise NotImplementedError
191
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700192 def close(self):
193 """Close the loop.
194
195 The loop should not be running.
196
197 This is idempotent and irreversible.
198
199 No other methods should be called after this one.
200 """
201 raise NotImplementedError
202
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200203 async def shutdown_asyncgens(self):
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400204 """Shutdown all active asynchronous generators."""
205 raise NotImplementedError
206
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700207 # Methods scheduling callbacks. All these return Handles.
208
Yury Selivanov592ada92014-09-25 12:07:56 -0400209 def _timer_handle_cancelled(self, handle):
210 """Notification that a TimerHandle has been cancelled."""
211 raise NotImplementedError
212
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700213 def call_soon(self, callback, *args):
214 return self.call_later(0, callback, *args)
215
216 def call_later(self, delay, callback, *args):
217 raise NotImplementedError
218
219 def call_at(self, when, callback, *args):
220 raise NotImplementedError
221
222 def time(self):
223 raise NotImplementedError
224
Yury Selivanov7661db62016-05-16 15:38:39 -0400225 def create_future(self):
226 raise NotImplementedError
227
Victor Stinner896a25a2014-07-08 11:29:25 +0200228 # Method scheduling a coroutine object: create a task.
229
230 def create_task(self, coro):
231 raise NotImplementedError
232
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700233 # Methods for interacting with threads.
234
235 def call_soon_threadsafe(self, callback, *args):
236 raise NotImplementedError
237
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200238 async def run_in_executor(self, executor, func, *args):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700239 raise NotImplementedError
240
241 def set_default_executor(self, executor):
242 raise NotImplementedError
243
244 # Network I/O methods returning Futures.
245
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200246 async def getaddrinfo(self, host, port, *,
247 family=0, type=0, proto=0, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700248 raise NotImplementedError
249
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200250 async def getnameinfo(self, sockaddr, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700251 raise NotImplementedError
252
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200253 async def create_connection(self, protocol_factory, host=None, port=None,
254 *, ssl=None, family=0, proto=0,
255 flags=0, sock=None, local_addr=None,
256 server_hostname=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700257 raise NotImplementedError
258
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200259 async def create_server(self, protocol_factory, host=None, port=None,
260 *, family=socket.AF_UNSPEC,
261 flags=socket.AI_PASSIVE, sock=None, backlog=100,
262 ssl=None, reuse_address=None, reuse_port=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700263 """A coroutine which creates a TCP server bound to host and port.
264
265 The return value is a Server object which can be used to stop
266 the service.
267
268 If host is an empty string or None all interfaces are assumed
269 and a list of multiple sockets will be returned (most likely
Yury Selivanov6370f342017-12-10 18:36:12 -0500270 one for IPv4 and another one for IPv6). The host parameter can also be
271 a sequence (e.g. list) of hosts to bind to.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700272
273 family can be set to either AF_INET or AF_INET6 to force the
274 socket to use IPv4 or IPv6. If not set it will be determined
275 from host (defaults to AF_UNSPEC).
276
277 flags is a bitmask for getaddrinfo().
278
279 sock can optionally be specified in order to use a preexisting
280 socket object.
281
282 backlog is the maximum number of queued connections passed to
283 listen() (defaults to 100).
284
285 ssl can be set to an SSLContext to enable SSL over the
286 accepted connections.
287
288 reuse_address tells the kernel to reuse a local socket in
289 TIME_WAIT state, without waiting for its natural timeout to
290 expire. If not specified will automatically be set to True on
291 UNIX.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700292
293 reuse_port tells the kernel to allow this endpoint to be bound to
294 the same port as other existing endpoints are bound to, so long as
295 they all set this flag when being created. This option is not
296 supported on Windows.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700297 """
298 raise NotImplementedError
299
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200300 async def create_unix_connection(self, protocol_factory, path=None, *,
301 ssl=None, sock=None,
302 server_hostname=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500303 raise NotImplementedError
304
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200305 async def create_unix_server(self, protocol_factory, path=None, *,
306 sock=None, backlog=100, ssl=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500307 """A coroutine which creates a UNIX Domain Socket server.
308
Yury Selivanovdec1a452014-02-18 22:27:48 -0500309 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500310 the service.
311
312 path is a str, representing a file systsem path to bind the
313 server socket to.
314
315 sock can optionally be specified in order to use a preexisting
316 socket object.
317
318 backlog is the maximum number of queued connections passed to
319 listen() (defaults to 100).
320
321 ssl can be set to an SSLContext to enable SSL over the
322 accepted connections.
323 """
324 raise NotImplementedError
325
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200326 async def create_datagram_endpoint(self, protocol_factory,
327 local_addr=None, remote_addr=None, *,
328 family=0, proto=0, flags=0,
329 reuse_address=None, reuse_port=None,
330 allow_broadcast=None, sock=None):
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700331 """A coroutine which creates a datagram endpoint.
332
333 This method will try to establish the endpoint in the background.
334 When successful, the coroutine returns a (transport, protocol) pair.
335
336 protocol_factory must be a callable returning a protocol instance.
337
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100338 socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
339 host (or family if specified), socket type SOCK_DGRAM.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700340
341 reuse_address tells the kernel to reuse a local socket in
342 TIME_WAIT state, without waiting for its natural timeout to
343 expire. If not specified it will automatically be set to True on
344 UNIX.
345
346 reuse_port tells the kernel to allow this endpoint to be bound to
347 the same port as other existing endpoints are bound to, so long as
348 they all set this flag when being created. This option is not
349 supported on Windows and some UNIX's. If the
350 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
351 capability is unsupported.
352
353 allow_broadcast tells the kernel to allow this endpoint to send
354 messages to the broadcast address.
355
356 sock can optionally be specified in order to use a preexisting
357 socket object.
358 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700359 raise NotImplementedError
360
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700361 # Pipes and subprocesses.
362
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200363 async def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200364 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700365
366 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200367 pipe is a file-like object.
368 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800369 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700370 # The reason to accept file-like object instead of just file descriptor
371 # is: we need to own pipe and close it at transport finishing
372 # Can got complicated errors if pass f.fileno(),
373 # close fd in pipe transport then close f and vise versa.
374 raise NotImplementedError
375
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200376 async def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500377 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700378
379 protocol_factory should instantiate object with BaseProtocol interface.
380 Pipe is file-like object already switched to nonblocking.
381 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800382 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700383 # The reason to accept file-like object instead of just file descriptor
384 # is: we need to own pipe and close it at transport finishing
385 # Can got complicated errors if pass f.fileno(),
386 # close fd in pipe transport then close f and vise versa.
387 raise NotImplementedError
388
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200389 async def subprocess_shell(self, protocol_factory, cmd, *,
390 stdin=subprocess.PIPE,
391 stdout=subprocess.PIPE,
392 stderr=subprocess.PIPE,
393 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700394 raise NotImplementedError
395
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200396 async def subprocess_exec(self, protocol_factory, *args,
397 stdin=subprocess.PIPE,
398 stdout=subprocess.PIPE,
399 stderr=subprocess.PIPE,
400 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700401 raise NotImplementedError
402
403 # Ready-based callback registration methods.
404 # The add_*() methods return None.
405 # The remove_*() methods return True if something was removed,
406 # False if there was nothing to delete.
407
408 def add_reader(self, fd, callback, *args):
409 raise NotImplementedError
410
411 def remove_reader(self, fd):
412 raise NotImplementedError
413
414 def add_writer(self, fd, callback, *args):
415 raise NotImplementedError
416
417 def remove_writer(self, fd):
418 raise NotImplementedError
419
420 # Completion based I/O methods returning Futures.
421
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200422 async def sock_recv(self, sock, nbytes):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700423 raise NotImplementedError
424
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200425 async def sock_recv_into(self, sock, buf):
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200426 raise NotImplementedError
427
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200428 async def sock_sendall(self, sock, data):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700429 raise NotImplementedError
430
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200431 async def sock_connect(self, sock, address):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700432 raise NotImplementedError
433
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200434 async def sock_accept(self, sock):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700435 raise NotImplementedError
436
437 # Signal handling.
438
439 def add_signal_handler(self, sig, callback, *args):
440 raise NotImplementedError
441
442 def remove_signal_handler(self, sig):
443 raise NotImplementedError
444
Yury Selivanov740169c2015-05-11 14:23:38 -0400445 # Task factory.
446
447 def set_task_factory(self, factory):
448 raise NotImplementedError
449
450 def get_task_factory(self):
451 raise NotImplementedError
452
Yury Selivanov569efa22014-02-18 18:02:19 -0500453 # Error handlers.
454
Yury Selivanov7ed7ce62016-05-16 15:20:38 -0400455 def get_exception_handler(self):
456 raise NotImplementedError
457
Yury Selivanov569efa22014-02-18 18:02:19 -0500458 def set_exception_handler(self, handler):
459 raise NotImplementedError
460
461 def default_exception_handler(self, context):
462 raise NotImplementedError
463
464 def call_exception_handler(self, context):
465 raise NotImplementedError
466
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100467 # Debug flag management.
468
469 def get_debug(self):
470 raise NotImplementedError
471
472 def set_debug(self, enabled):
473 raise NotImplementedError
474
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700475
476class AbstractEventLoopPolicy:
477 """Abstract policy for accessing the event loop."""
478
479 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200480 """Get the event loop for the current context.
481
482 Returns an event loop object implementing the BaseEventLoop interface,
483 or raises an exception in case no event loop has been set for the
484 current context and the current policy does not specify to create one.
485
486 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700487 raise NotImplementedError
488
489 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200490 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700491 raise NotImplementedError
492
493 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200494 """Create and return a new event loop object according to this
495 policy's rules. If there's need to set this loop as the event loop for
496 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700497 raise NotImplementedError
498
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800499 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700500
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800501 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200502 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800503 raise NotImplementedError
504
505 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200506 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800507 raise NotImplementedError
508
509
510class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700511 """Default policy implementation for accessing the event loop.
512
513 In this policy, each thread has its own event loop. However, we
514 only automatically create an event loop by default for the main
515 thread; other threads by default have no event loop.
516
517 Other policies may have different rules (e.g. a single global
518 event loop, or automatically creating an event loop per thread, or
519 using some other notion of context to which an event loop is
520 associated).
521 """
522
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800523 _loop_factory = None
524
525 class _Local(threading.local):
526 _loop = None
527 _set_called = False
528
529 def __init__(self):
530 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700531
532 def get_event_loop(self):
533 """Get the event loop.
534
535 This may be None or an instance of EventLoop.
536 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800537 if (self._local._loop is None and
Yury Selivanov6370f342017-12-10 18:36:12 -0500538 not self._local._set_called and
539 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800540 self.set_event_loop(self.new_event_loop())
Yury Selivanov6370f342017-12-10 18:36:12 -0500541
Victor Stinner3a1c7382014-12-18 01:20:10 +0100542 if self._local._loop is None:
543 raise RuntimeError('There is no current event loop in thread %r.'
544 % threading.current_thread().name)
Yury Selivanov6370f342017-12-10 18:36:12 -0500545
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800546 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700547
548 def set_event_loop(self, loop):
549 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800550 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700551 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800552 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700553
554 def new_event_loop(self):
555 """Create a new event loop.
556
557 You must call set_event_loop() to make this the current event
558 loop.
559 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800560 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700561
562
563# Event loop policy. The policy itself is always global, even if the
564# policy's rules say that there is an event loop per thread (or other
565# notion of context). The default policy is installed by the first
566# call to get_event_loop_policy().
567_event_loop_policy = None
568
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800569# Lock for protecting the on-the-fly creation of the event loop policy.
570_lock = threading.Lock()
571
572
Yury Selivanov600a3492016-11-04 14:29:28 -0400573# A TLS for the running event loop, used by _get_running_loop.
574class _RunningLoop(threading.local):
jimmylai80bbe6a72017-09-05 17:36:59 -0700575 loop_pid = (None, None)
Yury Selivanovba7e1f92017-03-02 20:07:11 -0500576
577
Yury Selivanov600a3492016-11-04 14:29:28 -0400578_running_loop = _RunningLoop()
579
580
Yury Selivanovabae67e2017-12-11 10:07:44 -0500581def get_running_loop():
582 """Return the running event loop. Raise a RuntimeError if there is none.
583
584 This function is thread-specific.
585 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500586 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanovabae67e2017-12-11 10:07:44 -0500587 loop = _get_running_loop()
588 if loop is None:
589 raise RuntimeError('no running event loop')
590 return loop
591
592
Yury Selivanov600a3492016-11-04 14:29:28 -0400593def _get_running_loop():
594 """Return the running event loop or None.
595
596 This is a low-level function intended to be used by event loops.
597 This function is thread-specific.
598 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500599 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700600 running_loop, pid = _running_loop.loop_pid
601 if running_loop is not None and pid == os.getpid():
Yury Selivanov902e9c52017-03-02 23:57:33 -0500602 return running_loop
Yury Selivanov600a3492016-11-04 14:29:28 -0400603
604
605def _set_running_loop(loop):
606 """Set the running event loop.
607
608 This is a low-level function intended to be used by event loops.
609 This function is thread-specific.
610 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500611 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700612 _running_loop.loop_pid = (loop, os.getpid())
Yury Selivanov600a3492016-11-04 14:29:28 -0400613
614
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800615def _init_event_loop_policy():
616 global _event_loop_policy
617 with _lock:
618 if _event_loop_policy is None: # pragma: no branch
619 from . import DefaultEventLoopPolicy
620 _event_loop_policy = DefaultEventLoopPolicy()
621
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700622
623def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200624 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700625 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800626 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700627 return _event_loop_policy
628
629
630def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200631 """Set the current event loop policy.
632
633 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700634 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700635 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
636 _event_loop_policy = policy
637
638
639def get_event_loop():
Yury Selivanov600a3492016-11-04 14:29:28 -0400640 """Return an asyncio event loop.
641
642 When called from a coroutine or a callback (e.g. scheduled with call_soon
643 or similar API), this function will always return the running event loop.
644
645 If there is no running event loop set, the function will return
646 the result of `get_event_loop_policy().get_event_loop()` call.
647 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500648 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanov600a3492016-11-04 14:29:28 -0400649 current_loop = _get_running_loop()
650 if current_loop is not None:
651 return current_loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700652 return get_event_loop_policy().get_event_loop()
653
654
655def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200656 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700657 get_event_loop_policy().set_event_loop(loop)
658
659
660def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200661 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700662 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800663
664
665def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200666 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800667 return get_event_loop_policy().get_child_watcher()
668
669
670def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200671 """Equivalent to calling
672 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800673 return get_event_loop_policy().set_child_watcher(watcher)
Yury Selivanova70232f2017-12-13 14:49:42 -0500674
675
676# Alias pure-Python implementations for testing purposes.
677_py__get_running_loop = _get_running_loop
678_py__set_running_loop = _set_running_loop
679_py_get_running_loop = get_running_loop
680_py_get_event_loop = get_event_loop
681
682
683try:
684 # get_event_loop() is one of the most frequently called
685 # functions in asyncio. Pure Python implementation is
686 # about 4 times slower than C-accelerated.
687 from _asyncio import (_get_running_loop, _set_running_loop,
688 get_running_loop, get_event_loop)
689except ImportError:
690 pass
691else:
692 # Alias C implementations for testing purposes.
693 _c__get_running_loop = _get_running_loop
694 _c__set_running_loop = _set_running_loop
695 _c_get_running_loop = get_running_loop
696 _c_get_event_loop = get_event_loop