Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 1 | """Event loop and event loop policy.""" |
| 2 | |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 3 | __all__ = ['AbstractEventLoopPolicy', |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 4 | 'AbstractEventLoop', 'AbstractServer', |
| 5 | 'Handle', 'TimerHandle', |
| 6 | 'get_event_loop_policy', 'set_event_loop_policy', |
| 7 | 'get_event_loop', 'set_event_loop', 'new_event_loop', |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 8 | 'get_child_watcher', 'set_child_watcher', |
Yury Selivanov | 6ea2b8f | 2016-11-07 19:00:46 -0500 | [diff] [blame] | 9 | '_set_running_loop', '_get_running_loop', |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 10 | ] |
| 11 | |
Victor Stinner | 307bccc | 2014-06-12 18:39:26 +0200 | [diff] [blame] | 12 | import functools |
| 13 | import inspect |
Yury Selivanov | ba7e1f9 | 2017-03-02 20:07:11 -0500 | [diff] [blame] | 14 | import os |
Victor Stinner | 313a980 | 2014-07-29 12:58:23 +0200 | [diff] [blame] | 15 | import reprlib |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 16 | import socket |
Victor Stinner | 313a980 | 2014-07-29 12:58:23 +0200 | [diff] [blame] | 17 | import subprocess |
Victor Stinner | 307bccc | 2014-06-12 18:39:26 +0200 | [diff] [blame] | 18 | import sys |
Victor Stinner | 313a980 | 2014-07-29 12:58:23 +0200 | [diff] [blame] | 19 | import threading |
| 20 | import traceback |
Victor Stinner | 307bccc | 2014-06-12 18:39:26 +0200 | [diff] [blame] | 21 | |
Antoine Pitrou | 921e943 | 2017-11-07 17:23:29 +0100 | [diff] [blame] | 22 | from . import constants |
| 23 | |
Victor Stinner | 975735f | 2014-06-25 21:41:58 +0200 | [diff] [blame] | 24 | |
Victor Stinner | 307bccc | 2014-06-12 18:39:26 +0200 | [diff] [blame] | 25 | def _get_function_source(func): |
INADA Naoki | 3e2ad8e | 2017-04-25 10:57:18 +0900 | [diff] [blame] | 26 | func = inspect.unwrap(func) |
Victor Stinner | 307bccc | 2014-06-12 18:39:26 +0200 | [diff] [blame] | 27 | if inspect.isfunction(func): |
| 28 | code = func.__code__ |
| 29 | return (code.co_filename, code.co_firstlineno) |
| 30 | if isinstance(func, functools.partial): |
| 31 | return _get_function_source(func.func) |
INADA Naoki | 3e2ad8e | 2017-04-25 10:57:18 +0900 | [diff] [blame] | 32 | if isinstance(func, functools.partialmethod): |
Victor Stinner | 307bccc | 2014-06-12 18:39:26 +0200 | [diff] [blame] | 33 | return _get_function_source(func.func) |
| 34 | return None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 35 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 36 | |
Yury Selivanov | 45dccda | 2016-09-15 15:58:15 -0400 | [diff] [blame] | 37 | def _format_args_and_kwargs(args, kwargs): |
| 38 | """Format function arguments and keyword arguments. |
Victor Stinner | 313a980 | 2014-07-29 12:58:23 +0200 | [diff] [blame] | 39 | |
| 40 | Special case for a single parameter: ('hello',) is formatted as ('hello'). |
| 41 | """ |
| 42 | # use reprlib to limit the length of the output |
Yury Selivanov | 45dccda | 2016-09-15 15:58:15 -0400 | [diff] [blame] | 43 | items = [] |
| 44 | if args: |
| 45 | items.extend(reprlib.repr(arg) for arg in args) |
| 46 | if kwargs: |
| 47 | items.extend('{}={}'.format(k, reprlib.repr(v)) |
| 48 | for k, v in kwargs.items()) |
| 49 | return '(' + ', '.join(items) + ')' |
Victor Stinner | 975735f | 2014-06-25 21:41:58 +0200 | [diff] [blame] | 50 | |
| 51 | |
Yury Selivanov | 45dccda | 2016-09-15 15:58:15 -0400 | [diff] [blame] | 52 | def _format_callback(func, args, kwargs, suffix=''): |
Victor Stinner | 975735f | 2014-06-25 21:41:58 +0200 | [diff] [blame] | 53 | if isinstance(func, functools.partial): |
Yury Selivanov | 45dccda | 2016-09-15 15:58:15 -0400 | [diff] [blame] | 54 | suffix = _format_args_and_kwargs(args, kwargs) + suffix |
| 55 | return _format_callback(func.func, func.args, func.keywords, suffix) |
Victor Stinner | 975735f | 2014-06-25 21:41:58 +0200 | [diff] [blame] | 56 | |
Guido van Rossum | 0a9933e | 2015-05-02 18:38:24 -0700 | [diff] [blame] | 57 | if hasattr(func, '__qualname__'): |
| 58 | func_repr = getattr(func, '__qualname__') |
| 59 | elif hasattr(func, '__name__'): |
| 60 | func_repr = getattr(func, '__name__') |
| 61 | else: |
Victor Stinner | 975735f | 2014-06-25 21:41:58 +0200 | [diff] [blame] | 62 | func_repr = repr(func) |
| 63 | |
Yury Selivanov | 45dccda | 2016-09-15 15:58:15 -0400 | [diff] [blame] | 64 | func_repr += _format_args_and_kwargs(args, kwargs) |
Victor Stinner | 975735f | 2014-06-25 21:41:58 +0200 | [diff] [blame] | 65 | if suffix: |
| 66 | func_repr += suffix |
Guido van Rossum | 0a9933e | 2015-05-02 18:38:24 -0700 | [diff] [blame] | 67 | return func_repr |
Victor Stinner | 975735f | 2014-06-25 21:41:58 +0200 | [diff] [blame] | 68 | |
Guido van Rossum | 0a9933e | 2015-05-02 18:38:24 -0700 | [diff] [blame] | 69 | def _format_callback_source(func, args): |
Yury Selivanov | 45dccda | 2016-09-15 15:58:15 -0400 | [diff] [blame] | 70 | func_repr = _format_callback(func, args, None) |
Victor Stinner | 975735f | 2014-06-25 21:41:58 +0200 | [diff] [blame] | 71 | source = _get_function_source(func) |
| 72 | if source: |
| 73 | func_repr += ' at %s:%s' % source |
| 74 | return func_repr |
| 75 | |
| 76 | |
Antoine Pitrou | 921e943 | 2017-11-07 17:23:29 +0100 | [diff] [blame] | 77 | def extract_stack(f=None, limit=None): |
| 78 | """Replacement for traceback.extract_stack() that only does the |
| 79 | necessary work for asyncio debug mode. |
| 80 | """ |
| 81 | if f is None: |
| 82 | f = sys._getframe().f_back |
| 83 | if limit is None: |
| 84 | # Limit the amount of work to a reasonable amount, as extract_stack() |
| 85 | # can be called for each coroutine and future in debug mode. |
| 86 | limit = constants.DEBUG_STACK_DEPTH |
| 87 | stack = traceback.StackSummary.extract(traceback.walk_stack(f), |
| 88 | limit=limit, |
| 89 | lookup_lines=False) |
| 90 | stack.reverse() |
| 91 | return stack |
| 92 | |
| 93 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 94 | class Handle: |
| 95 | """Object returned by callback registration methods.""" |
| 96 | |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 97 | __slots__ = ('_callback', '_args', '_cancelled', '_loop', |
Victor Stinner | 1b38bc6 | 2014-09-17 23:24:13 +0200 | [diff] [blame] | 98 | '_source_traceback', '_repr', '__weakref__') |
Yury Selivanov | b131778 | 2014-02-12 17:01:52 -0500 | [diff] [blame] | 99 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 100 | def __init__(self, callback, args, loop): |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 101 | self._loop = loop |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 102 | self._callback = callback |
| 103 | self._args = args |
| 104 | self._cancelled = False |
Victor Stinner | 1b38bc6 | 2014-09-17 23:24:13 +0200 | [diff] [blame] | 105 | self._repr = None |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 106 | if self._loop.get_debug(): |
Antoine Pitrou | 921e943 | 2017-11-07 17:23:29 +0100 | [diff] [blame] | 107 | self._source_traceback = extract_stack(sys._getframe(1)) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 108 | else: |
| 109 | self._source_traceback = None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 110 | |
Victor Stinner | 1b38bc6 | 2014-09-17 23:24:13 +0200 | [diff] [blame] | 111 | def _repr_info(self): |
Victor Stinner | f68bd88 | 2014-07-10 22:32:58 +0200 | [diff] [blame] | 112 | info = [self.__class__.__name__] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 113 | if self._cancelled: |
Victor Stinner | 975735f | 2014-06-25 21:41:58 +0200 | [diff] [blame] | 114 | info.append('cancelled') |
Victor Stinner | f68bd88 | 2014-07-10 22:32:58 +0200 | [diff] [blame] | 115 | if self._callback is not None: |
Guido van Rossum | 0a9933e | 2015-05-02 18:38:24 -0700 | [diff] [blame] | 116 | info.append(_format_callback_source(self._callback, self._args)) |
Victor Stinner | f68bd88 | 2014-07-10 22:32:58 +0200 | [diff] [blame] | 117 | if self._source_traceback: |
| 118 | frame = self._source_traceback[-1] |
| 119 | info.append('created at %s:%s' % (frame[0], frame[1])) |
Victor Stinner | 1b38bc6 | 2014-09-17 23:24:13 +0200 | [diff] [blame] | 120 | return info |
| 121 | |
| 122 | def __repr__(self): |
| 123 | if self._repr is not None: |
| 124 | return self._repr |
| 125 | info = self._repr_info() |
Victor Stinner | f68bd88 | 2014-07-10 22:32:58 +0200 | [diff] [blame] | 126 | return '<%s>' % ' '.join(info) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 127 | |
| 128 | def cancel(self): |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 129 | if not self._cancelled: |
| 130 | self._cancelled = True |
| 131 | if self._loop.get_debug(): |
| 132 | # Keep a representation in debug mode to keep callback and |
| 133 | # parameters. For example, to log the warning |
| 134 | # "Executing <Handle...> took 2.5 second" |
| 135 | self._repr = repr(self) |
| 136 | self._callback = None |
| 137 | self._args = None |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 138 | |
Marat Sharafutdinov | 69cfed1 | 2017-11-07 12:06:05 +0300 | [diff] [blame] | 139 | def cancelled(self): |
| 140 | return self._cancelled |
| 141 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 142 | def _run(self): |
| 143 | try: |
| 144 | self._callback(*self._args) |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 145 | except Exception as exc: |
Guido van Rossum | 0a9933e | 2015-05-02 18:38:24 -0700 | [diff] [blame] | 146 | cb = _format_callback_source(self._callback, self._args) |
Victor Stinner | 17b53f1 | 2014-06-26 01:35:45 +0200 | [diff] [blame] | 147 | msg = 'Exception in callback {}'.format(cb) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 148 | context = { |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 149 | 'message': msg, |
| 150 | 'exception': exc, |
| 151 | 'handle': self, |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 152 | } |
| 153 | if self._source_traceback: |
| 154 | context['source_traceback'] = self._source_traceback |
| 155 | self._loop.call_exception_handler(context) |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 156 | self = None # Needed to break cycles when an exception occurs. |
| 157 | |
| 158 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 159 | class TimerHandle(Handle): |
| 160 | """Object returned by timed callback registration methods.""" |
| 161 | |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 162 | __slots__ = ['_scheduled', '_when'] |
Yury Selivanov | b131778 | 2014-02-12 17:01:52 -0500 | [diff] [blame] | 163 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 164 | def __init__(self, when, callback, args, loop): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 165 | assert when is not None |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 166 | super().__init__(callback, args, loop) |
Victor Stinner | 80f53aa | 2014-06-27 13:52:20 +0200 | [diff] [blame] | 167 | if self._source_traceback: |
| 168 | del self._source_traceback[-1] |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 169 | self._when = when |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 170 | self._scheduled = False |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 171 | |
Victor Stinner | 1b38bc6 | 2014-09-17 23:24:13 +0200 | [diff] [blame] | 172 | def _repr_info(self): |
| 173 | info = super()._repr_info() |
| 174 | pos = 2 if self._cancelled else 1 |
| 175 | info.insert(pos, 'when=%s' % self._when) |
| 176 | return info |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 177 | |
| 178 | def __hash__(self): |
| 179 | return hash(self._when) |
| 180 | |
| 181 | def __lt__(self, other): |
| 182 | return self._when < other._when |
| 183 | |
| 184 | def __le__(self, other): |
| 185 | if self._when < other._when: |
| 186 | return True |
| 187 | return self.__eq__(other) |
| 188 | |
| 189 | def __gt__(self, other): |
| 190 | return self._when > other._when |
| 191 | |
| 192 | def __ge__(self, other): |
| 193 | if self._when > other._when: |
| 194 | return True |
| 195 | return self.__eq__(other) |
| 196 | |
| 197 | def __eq__(self, other): |
| 198 | if isinstance(other, TimerHandle): |
| 199 | return (self._when == other._when and |
| 200 | self._callback == other._callback and |
| 201 | self._args == other._args and |
| 202 | self._cancelled == other._cancelled) |
| 203 | return NotImplemented |
| 204 | |
| 205 | def __ne__(self, other): |
| 206 | equal = self.__eq__(other) |
| 207 | return NotImplemented if equal is NotImplemented else not equal |
| 208 | |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 209 | def cancel(self): |
| 210 | if not self._cancelled: |
| 211 | self._loop._timer_handle_cancelled(self) |
| 212 | super().cancel() |
| 213 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 214 | |
| 215 | class AbstractServer: |
Victor Stinner | cf6f72e | 2013-12-03 18:23:52 +0100 | [diff] [blame] | 216 | """Abstract server returned by create_server().""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 217 | |
| 218 | def close(self): |
| 219 | """Stop serving. This leaves existing connections open.""" |
| 220 | return NotImplemented |
| 221 | |
| 222 | def wait_closed(self): |
| 223 | """Coroutine to wait until service is closed.""" |
| 224 | return NotImplemented |
| 225 | |
| 226 | |
| 227 | class AbstractEventLoop: |
| 228 | """Abstract event loop.""" |
| 229 | |
| 230 | # Running and stopping the event loop. |
| 231 | |
| 232 | def run_forever(self): |
| 233 | """Run the event loop until stop() is called.""" |
| 234 | raise NotImplementedError |
| 235 | |
| 236 | def run_until_complete(self, future): |
| 237 | """Run the event loop until a Future is done. |
| 238 | |
| 239 | Return the Future's result, or raise its exception. |
| 240 | """ |
| 241 | raise NotImplementedError |
| 242 | |
| 243 | def stop(self): |
| 244 | """Stop the event loop as soon as reasonable. |
| 245 | |
| 246 | Exactly how soon that is may depend on the implementation, but |
| 247 | no more I/O callbacks should be scheduled. |
| 248 | """ |
| 249 | raise NotImplementedError |
| 250 | |
| 251 | def is_running(self): |
| 252 | """Return whether the event loop is currently running.""" |
| 253 | raise NotImplementedError |
| 254 | |
Victor Stinner | 896a25a | 2014-07-08 11:29:25 +0200 | [diff] [blame] | 255 | def is_closed(self): |
| 256 | """Returns True if the event loop was closed.""" |
| 257 | raise NotImplementedError |
| 258 | |
Guido van Rossum | e3f52ef | 2013-11-01 14:19:04 -0700 | [diff] [blame] | 259 | def close(self): |
| 260 | """Close the loop. |
| 261 | |
| 262 | The loop should not be running. |
| 263 | |
| 264 | This is idempotent and irreversible. |
| 265 | |
| 266 | No other methods should be called after this one. |
| 267 | """ |
| 268 | raise NotImplementedError |
| 269 | |
Yury Selivanov | f6d991d | 2016-09-15 13:10:51 -0400 | [diff] [blame] | 270 | def shutdown_asyncgens(self): |
| 271 | """Shutdown all active asynchronous generators.""" |
| 272 | raise NotImplementedError |
| 273 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 274 | # Methods scheduling callbacks. All these return Handles. |
| 275 | |
Yury Selivanov | 592ada9 | 2014-09-25 12:07:56 -0400 | [diff] [blame] | 276 | def _timer_handle_cancelled(self, handle): |
| 277 | """Notification that a TimerHandle has been cancelled.""" |
| 278 | raise NotImplementedError |
| 279 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 280 | def call_soon(self, callback, *args): |
| 281 | return self.call_later(0, callback, *args) |
| 282 | |
| 283 | def call_later(self, delay, callback, *args): |
| 284 | raise NotImplementedError |
| 285 | |
| 286 | def call_at(self, when, callback, *args): |
| 287 | raise NotImplementedError |
| 288 | |
| 289 | def time(self): |
| 290 | raise NotImplementedError |
| 291 | |
Yury Selivanov | 7661db6 | 2016-05-16 15:38:39 -0400 | [diff] [blame] | 292 | def create_future(self): |
| 293 | raise NotImplementedError |
| 294 | |
Victor Stinner | 896a25a | 2014-07-08 11:29:25 +0200 | [diff] [blame] | 295 | # Method scheduling a coroutine object: create a task. |
| 296 | |
| 297 | def create_task(self, coro): |
| 298 | raise NotImplementedError |
| 299 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 300 | # Methods for interacting with threads. |
| 301 | |
| 302 | def call_soon_threadsafe(self, callback, *args): |
| 303 | raise NotImplementedError |
| 304 | |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 305 | def run_in_executor(self, executor, func, *args): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 306 | raise NotImplementedError |
| 307 | |
| 308 | def set_default_executor(self, executor): |
| 309 | raise NotImplementedError |
| 310 | |
| 311 | # Network I/O methods returning Futures. |
| 312 | |
| 313 | def getaddrinfo(self, host, port, *, family=0, type=0, proto=0, flags=0): |
| 314 | raise NotImplementedError |
| 315 | |
| 316 | def getnameinfo(self, sockaddr, flags=0): |
| 317 | raise NotImplementedError |
| 318 | |
| 319 | def create_connection(self, protocol_factory, host=None, port=None, *, |
| 320 | ssl=None, family=0, proto=0, flags=0, sock=None, |
Guido van Rossum | 21c85a7 | 2013-11-01 14:16:54 -0700 | [diff] [blame] | 321 | local_addr=None, server_hostname=None): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 322 | raise NotImplementedError |
| 323 | |
| 324 | def create_server(self, protocol_factory, host=None, port=None, *, |
| 325 | family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 326 | sock=None, backlog=100, ssl=None, reuse_address=None, |
| 327 | reuse_port=None): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 328 | """A coroutine which creates a TCP server bound to host and port. |
| 329 | |
| 330 | The return value is a Server object which can be used to stop |
| 331 | the service. |
| 332 | |
| 333 | If host is an empty string or None all interfaces are assumed |
| 334 | and a list of multiple sockets will be returned (most likely |
Victor Stinner | 5e4a7d8 | 2015-09-21 18:33:43 +0200 | [diff] [blame] | 335 | one for IPv4 and another one for IPv6). The host parameter can also be a |
| 336 | sequence (e.g. list) of hosts to bind to. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 337 | |
| 338 | family can be set to either AF_INET or AF_INET6 to force the |
| 339 | socket to use IPv4 or IPv6. If not set it will be determined |
| 340 | from host (defaults to AF_UNSPEC). |
| 341 | |
| 342 | flags is a bitmask for getaddrinfo(). |
| 343 | |
| 344 | sock can optionally be specified in order to use a preexisting |
| 345 | socket object. |
| 346 | |
| 347 | backlog is the maximum number of queued connections passed to |
| 348 | listen() (defaults to 100). |
| 349 | |
| 350 | ssl can be set to an SSLContext to enable SSL over the |
| 351 | accepted connections. |
| 352 | |
| 353 | reuse_address tells the kernel to reuse a local socket in |
| 354 | TIME_WAIT state, without waiting for its natural timeout to |
| 355 | expire. If not specified will automatically be set to True on |
| 356 | UNIX. |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 357 | |
| 358 | reuse_port tells the kernel to allow this endpoint to be bound to |
| 359 | the same port as other existing endpoints are bound to, so long as |
| 360 | they all set this flag when being created. This option is not |
| 361 | supported on Windows. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 362 | """ |
| 363 | raise NotImplementedError |
| 364 | |
Yury Selivanov | 423fd36 | 2017-11-20 17:26:28 -0500 | [diff] [blame] | 365 | def create_unix_connection(self, protocol_factory, path=None, *, |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 366 | ssl=None, sock=None, |
| 367 | server_hostname=None): |
| 368 | raise NotImplementedError |
| 369 | |
Yury Selivanov | 423fd36 | 2017-11-20 17:26:28 -0500 | [diff] [blame] | 370 | def create_unix_server(self, protocol_factory, path=None, *, |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 371 | sock=None, backlog=100, ssl=None): |
| 372 | """A coroutine which creates a UNIX Domain Socket server. |
| 373 | |
Yury Selivanov | dec1a45 | 2014-02-18 22:27:48 -0500 | [diff] [blame] | 374 | The return value is a Server object, which can be used to stop |
Yury Selivanov | b057c52 | 2014-02-18 12:15:06 -0500 | [diff] [blame] | 375 | the service. |
| 376 | |
| 377 | path is a str, representing a file systsem path to bind the |
| 378 | server socket to. |
| 379 | |
| 380 | sock can optionally be specified in order to use a preexisting |
| 381 | socket object. |
| 382 | |
| 383 | backlog is the maximum number of queued connections passed to |
| 384 | listen() (defaults to 100). |
| 385 | |
| 386 | ssl can be set to an SSLContext to enable SSL over the |
| 387 | accepted connections. |
| 388 | """ |
| 389 | raise NotImplementedError |
| 390 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 391 | def create_datagram_endpoint(self, protocol_factory, |
| 392 | local_addr=None, remote_addr=None, *, |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 393 | family=0, proto=0, flags=0, |
| 394 | reuse_address=None, reuse_port=None, |
| 395 | allow_broadcast=None, sock=None): |
| 396 | """A coroutine which creates a datagram endpoint. |
| 397 | |
| 398 | This method will try to establish the endpoint in the background. |
| 399 | When successful, the coroutine returns a (transport, protocol) pair. |
| 400 | |
| 401 | protocol_factory must be a callable returning a protocol instance. |
| 402 | |
Quentin Dawans | fe4ea9c | 2017-10-30 14:43:02 +0100 | [diff] [blame] | 403 | socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on |
| 404 | host (or family if specified), socket type SOCK_DGRAM. |
Guido van Rossum | b9bf913 | 2015-10-05 09:15:28 -0700 | [diff] [blame] | 405 | |
| 406 | reuse_address tells the kernel to reuse a local socket in |
| 407 | TIME_WAIT state, without waiting for its natural timeout to |
| 408 | expire. If not specified it will automatically be set to True on |
| 409 | UNIX. |
| 410 | |
| 411 | reuse_port tells the kernel to allow this endpoint to be bound to |
| 412 | the same port as other existing endpoints are bound to, so long as |
| 413 | they all set this flag when being created. This option is not |
| 414 | supported on Windows and some UNIX's. If the |
| 415 | :py:data:`~socket.SO_REUSEPORT` constant is not defined then this |
| 416 | capability is unsupported. |
| 417 | |
| 418 | allow_broadcast tells the kernel to allow this endpoint to send |
| 419 | messages to the broadcast address. |
| 420 | |
| 421 | sock can optionally be specified in order to use a preexisting |
| 422 | socket object. |
| 423 | """ |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 424 | raise NotImplementedError |
| 425 | |
Guido van Rossum | e3f52ef | 2013-11-01 14:19:04 -0700 | [diff] [blame] | 426 | # Pipes and subprocesses. |
| 427 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 428 | def connect_read_pipe(self, protocol_factory, pipe): |
Victor Stinner | a5b257a | 2014-05-29 00:14:03 +0200 | [diff] [blame] | 429 | """Register read pipe in event loop. Set the pipe to non-blocking mode. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 430 | |
| 431 | protocol_factory should instantiate object with Protocol interface. |
Victor Stinner | a5b257a | 2014-05-29 00:14:03 +0200 | [diff] [blame] | 432 | pipe is a file-like object. |
| 433 | Return pair (transport, protocol), where transport supports the |
Guido van Rossum | 9204af4 | 2013-11-30 15:35:42 -0800 | [diff] [blame] | 434 | ReadTransport interface.""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 435 | # The reason to accept file-like object instead of just file descriptor |
| 436 | # is: we need to own pipe and close it at transport finishing |
| 437 | # Can got complicated errors if pass f.fileno(), |
| 438 | # close fd in pipe transport then close f and vise versa. |
| 439 | raise NotImplementedError |
| 440 | |
| 441 | def connect_write_pipe(self, protocol_factory, pipe): |
Yury Selivanov | dec1a45 | 2014-02-18 22:27:48 -0500 | [diff] [blame] | 442 | """Register write pipe in event loop. |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 443 | |
| 444 | protocol_factory should instantiate object with BaseProtocol interface. |
| 445 | Pipe is file-like object already switched to nonblocking. |
| 446 | Return pair (transport, protocol), where transport support |
Guido van Rossum | 9204af4 | 2013-11-30 15:35:42 -0800 | [diff] [blame] | 447 | WriteTransport interface.""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 448 | # The reason to accept file-like object instead of just file descriptor |
| 449 | # is: we need to own pipe and close it at transport finishing |
| 450 | # Can got complicated errors if pass f.fileno(), |
| 451 | # close fd in pipe transport then close f and vise versa. |
| 452 | raise NotImplementedError |
| 453 | |
| 454 | def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE, |
| 455 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 456 | **kwargs): |
| 457 | raise NotImplementedError |
| 458 | |
| 459 | def subprocess_exec(self, protocol_factory, *args, stdin=subprocess.PIPE, |
| 460 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 461 | **kwargs): |
| 462 | raise NotImplementedError |
| 463 | |
| 464 | # Ready-based callback registration methods. |
| 465 | # The add_*() methods return None. |
| 466 | # The remove_*() methods return True if something was removed, |
| 467 | # False if there was nothing to delete. |
| 468 | |
| 469 | def add_reader(self, fd, callback, *args): |
| 470 | raise NotImplementedError |
| 471 | |
| 472 | def remove_reader(self, fd): |
| 473 | raise NotImplementedError |
| 474 | |
| 475 | def add_writer(self, fd, callback, *args): |
| 476 | raise NotImplementedError |
| 477 | |
| 478 | def remove_writer(self, fd): |
| 479 | raise NotImplementedError |
| 480 | |
| 481 | # Completion based I/O methods returning Futures. |
| 482 | |
| 483 | def sock_recv(self, sock, nbytes): |
| 484 | raise NotImplementedError |
| 485 | |
Antoine Pitrou | 525f40d | 2017-10-19 21:46:40 +0200 | [diff] [blame] | 486 | def sock_recv_into(self, sock, buf): |
| 487 | raise NotImplementedError |
| 488 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 489 | def sock_sendall(self, sock, data): |
| 490 | raise NotImplementedError |
| 491 | |
| 492 | def sock_connect(self, sock, address): |
| 493 | raise NotImplementedError |
| 494 | |
| 495 | def sock_accept(self, sock): |
| 496 | raise NotImplementedError |
| 497 | |
| 498 | # Signal handling. |
| 499 | |
| 500 | def add_signal_handler(self, sig, callback, *args): |
| 501 | raise NotImplementedError |
| 502 | |
| 503 | def remove_signal_handler(self, sig): |
| 504 | raise NotImplementedError |
| 505 | |
Yury Selivanov | 740169c | 2015-05-11 14:23:38 -0400 | [diff] [blame] | 506 | # Task factory. |
| 507 | |
| 508 | def set_task_factory(self, factory): |
| 509 | raise NotImplementedError |
| 510 | |
| 511 | def get_task_factory(self): |
| 512 | raise NotImplementedError |
| 513 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 514 | # Error handlers. |
| 515 | |
Yury Selivanov | 7ed7ce6 | 2016-05-16 15:20:38 -0400 | [diff] [blame] | 516 | def get_exception_handler(self): |
| 517 | raise NotImplementedError |
| 518 | |
Yury Selivanov | 569efa2 | 2014-02-18 18:02:19 -0500 | [diff] [blame] | 519 | def set_exception_handler(self, handler): |
| 520 | raise NotImplementedError |
| 521 | |
| 522 | def default_exception_handler(self, context): |
| 523 | raise NotImplementedError |
| 524 | |
| 525 | def call_exception_handler(self, context): |
| 526 | raise NotImplementedError |
| 527 | |
Victor Stinner | 0f3e6bc | 2014-02-19 23:15:02 +0100 | [diff] [blame] | 528 | # Debug flag management. |
| 529 | |
| 530 | def get_debug(self): |
| 531 | raise NotImplementedError |
| 532 | |
| 533 | def set_debug(self, enabled): |
| 534 | raise NotImplementedError |
| 535 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 536 | |
| 537 | class AbstractEventLoopPolicy: |
| 538 | """Abstract policy for accessing the event loop.""" |
| 539 | |
| 540 | def get_event_loop(self): |
Victor Stinner | f9e49dd | 2014-06-05 12:06:44 +0200 | [diff] [blame] | 541 | """Get the event loop for the current context. |
| 542 | |
| 543 | Returns an event loop object implementing the BaseEventLoop interface, |
| 544 | or raises an exception in case no event loop has been set for the |
| 545 | current context and the current policy does not specify to create one. |
| 546 | |
| 547 | It should never return None.""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 548 | raise NotImplementedError |
| 549 | |
| 550 | def set_event_loop(self, loop): |
Victor Stinner | f9e49dd | 2014-06-05 12:06:44 +0200 | [diff] [blame] | 551 | """Set the event loop for the current context to loop.""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 552 | raise NotImplementedError |
| 553 | |
| 554 | def new_event_loop(self): |
Victor Stinner | f9e49dd | 2014-06-05 12:06:44 +0200 | [diff] [blame] | 555 | """Create and return a new event loop object according to this |
| 556 | policy's rules. If there's need to set this loop as the event loop for |
| 557 | the current context, set_event_loop must be called explicitly.""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 558 | raise NotImplementedError |
| 559 | |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 560 | # Child processes handling (Unix only). |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 561 | |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 562 | def get_child_watcher(self): |
Victor Stinner | f9e49dd | 2014-06-05 12:06:44 +0200 | [diff] [blame] | 563 | "Get the watcher for child processes." |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 564 | raise NotImplementedError |
| 565 | |
| 566 | def set_child_watcher(self, watcher): |
Victor Stinner | f9e49dd | 2014-06-05 12:06:44 +0200 | [diff] [blame] | 567 | """Set the watcher for child processes.""" |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 568 | raise NotImplementedError |
| 569 | |
| 570 | |
| 571 | class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy): |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 572 | """Default policy implementation for accessing the event loop. |
| 573 | |
| 574 | In this policy, each thread has its own event loop. However, we |
| 575 | only automatically create an event loop by default for the main |
| 576 | thread; other threads by default have no event loop. |
| 577 | |
| 578 | Other policies may have different rules (e.g. a single global |
| 579 | event loop, or automatically creating an event loop per thread, or |
| 580 | using some other notion of context to which an event loop is |
| 581 | associated). |
| 582 | """ |
| 583 | |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 584 | _loop_factory = None |
| 585 | |
| 586 | class _Local(threading.local): |
| 587 | _loop = None |
| 588 | _set_called = False |
| 589 | |
| 590 | def __init__(self): |
| 591 | self._local = self._Local() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 592 | |
| 593 | def get_event_loop(self): |
| 594 | """Get the event loop. |
| 595 | |
| 596 | This may be None or an instance of EventLoop. |
| 597 | """ |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 598 | if (self._local._loop is None and |
| 599 | not self._local._set_called and |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 600 | isinstance(threading.current_thread(), threading._MainThread)): |
Guido van Rossum | cced076 | 2013-11-27 10:37:13 -0800 | [diff] [blame] | 601 | self.set_event_loop(self.new_event_loop()) |
Victor Stinner | 3a1c738 | 2014-12-18 01:20:10 +0100 | [diff] [blame] | 602 | if self._local._loop is None: |
| 603 | raise RuntimeError('There is no current event loop in thread %r.' |
| 604 | % threading.current_thread().name) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 605 | return self._local._loop |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 606 | |
| 607 | def set_event_loop(self, loop): |
| 608 | """Set the event loop.""" |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 609 | self._local._set_called = True |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 610 | assert loop is None or isinstance(loop, AbstractEventLoop) |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 611 | self._local._loop = loop |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 612 | |
| 613 | def new_event_loop(self): |
| 614 | """Create a new event loop. |
| 615 | |
| 616 | You must call set_event_loop() to make this the current event |
| 617 | loop. |
| 618 | """ |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 619 | return self._loop_factory() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 620 | |
| 621 | |
| 622 | # Event loop policy. The policy itself is always global, even if the |
| 623 | # policy's rules say that there is an event loop per thread (or other |
| 624 | # notion of context). The default policy is installed by the first |
| 625 | # call to get_event_loop_policy(). |
| 626 | _event_loop_policy = None |
| 627 | |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 628 | # Lock for protecting the on-the-fly creation of the event loop policy. |
| 629 | _lock = threading.Lock() |
| 630 | |
| 631 | |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 632 | # A TLS for the running event loop, used by _get_running_loop. |
| 633 | class _RunningLoop(threading.local): |
jimmylai | 80bbe6a7 | 2017-09-05 17:36:59 -0700 | [diff] [blame] | 634 | loop_pid = (None, None) |
Yury Selivanov | ba7e1f9 | 2017-03-02 20:07:11 -0500 | [diff] [blame] | 635 | |
| 636 | |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 637 | _running_loop = _RunningLoop() |
| 638 | |
| 639 | |
| 640 | def _get_running_loop(): |
| 641 | """Return the running event loop or None. |
| 642 | |
| 643 | This is a low-level function intended to be used by event loops. |
| 644 | This function is thread-specific. |
| 645 | """ |
jimmylai | 80bbe6a7 | 2017-09-05 17:36:59 -0700 | [diff] [blame] | 646 | running_loop, pid = _running_loop.loop_pid |
| 647 | if running_loop is not None and pid == os.getpid(): |
Yury Selivanov | 902e9c5 | 2017-03-02 23:57:33 -0500 | [diff] [blame] | 648 | return running_loop |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 649 | |
| 650 | |
| 651 | def _set_running_loop(loop): |
| 652 | """Set the running event loop. |
| 653 | |
| 654 | This is a low-level function intended to be used by event loops. |
| 655 | This function is thread-specific. |
| 656 | """ |
jimmylai | 80bbe6a7 | 2017-09-05 17:36:59 -0700 | [diff] [blame] | 657 | _running_loop.loop_pid = (loop, os.getpid()) |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 658 | |
| 659 | |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 660 | def _init_event_loop_policy(): |
| 661 | global _event_loop_policy |
| 662 | with _lock: |
| 663 | if _event_loop_policy is None: # pragma: no branch |
| 664 | from . import DefaultEventLoopPolicy |
| 665 | _event_loop_policy = DefaultEventLoopPolicy() |
| 666 | |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 667 | |
| 668 | def get_event_loop_policy(): |
Victor Stinner | f9e49dd | 2014-06-05 12:06:44 +0200 | [diff] [blame] | 669 | """Get the current event loop policy.""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 670 | if _event_loop_policy is None: |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 671 | _init_event_loop_policy() |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 672 | return _event_loop_policy |
| 673 | |
| 674 | |
| 675 | def set_event_loop_policy(policy): |
Victor Stinner | f9e49dd | 2014-06-05 12:06:44 +0200 | [diff] [blame] | 676 | """Set the current event loop policy. |
| 677 | |
| 678 | If policy is None, the default policy is restored.""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 679 | global _event_loop_policy |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 680 | assert policy is None or isinstance(policy, AbstractEventLoopPolicy) |
| 681 | _event_loop_policy = policy |
| 682 | |
| 683 | |
| 684 | def get_event_loop(): |
Yury Selivanov | 600a349 | 2016-11-04 14:29:28 -0400 | [diff] [blame] | 685 | """Return an asyncio event loop. |
| 686 | |
| 687 | When called from a coroutine or a callback (e.g. scheduled with call_soon |
| 688 | or similar API), this function will always return the running event loop. |
| 689 | |
| 690 | If there is no running event loop set, the function will return |
| 691 | the result of `get_event_loop_policy().get_event_loop()` call. |
| 692 | """ |
| 693 | current_loop = _get_running_loop() |
| 694 | if current_loop is not None: |
| 695 | return current_loop |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 696 | return get_event_loop_policy().get_event_loop() |
| 697 | |
| 698 | |
| 699 | def set_event_loop(loop): |
Victor Stinner | f9e49dd | 2014-06-05 12:06:44 +0200 | [diff] [blame] | 700 | """Equivalent to calling get_event_loop_policy().set_event_loop(loop).""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 701 | get_event_loop_policy().set_event_loop(loop) |
| 702 | |
| 703 | |
| 704 | def new_event_loop(): |
Victor Stinner | f9e49dd | 2014-06-05 12:06:44 +0200 | [diff] [blame] | 705 | """Equivalent to calling get_event_loop_policy().new_event_loop().""" |
Guido van Rossum | 27b7c7e | 2013-10-17 13:40:50 -0700 | [diff] [blame] | 706 | return get_event_loop_policy().new_event_loop() |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 707 | |
| 708 | |
| 709 | def get_child_watcher(): |
Victor Stinner | f9e49dd | 2014-06-05 12:06:44 +0200 | [diff] [blame] | 710 | """Equivalent to calling get_event_loop_policy().get_child_watcher().""" |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 711 | return get_event_loop_policy().get_child_watcher() |
| 712 | |
| 713 | |
| 714 | def set_child_watcher(watcher): |
Victor Stinner | f9e49dd | 2014-06-05 12:06:44 +0200 | [diff] [blame] | 715 | """Equivalent to calling |
| 716 | get_event_loop_policy().set_child_watcher(watcher).""" |
Guido van Rossum | 0eaa5ac | 2013-11-04 15:50:46 -0800 | [diff] [blame] | 717 | return get_event_loop_policy().set_child_watcher(watcher) |