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