Debian Codegraph @

pika/adapters/utils/selector_ioloop_adapter.py

raw
1 """
2 Implementation of `nbio_interface.AbstractIOServices` on top of a
3 selector-based I/O loop, such as tornado's and our home-grown
4 select_connection's I/O loops.
5
6 """
7 from __future__ import annotations
8
9 import abc
10 import logging
11 import socket
12 import threading
13 from typing import Any, Callable, Dict, Optional
14
15 from pika.adapters.utils import nbio_interface, io_services_utils
16 from pika.adapters.utils.io_services_utils import (check_callback_arg,
17 check_fd_arg)
18
19 LOGGER = logging.getLogger(__name__)
20
21
22 class AbstractSelectorIOLoop:
23 """Selector-based I/O loop interface expected by
24 `selector_ioloop_adapter.SelectorIOServicesAdapter`
25
26 NOTE: this interface follows the corresponding methods and attributes
27 of `tornado.ioloop.IOLoop` in order to avoid additional adapter layering
28 when wrapping tornado's IOLoop.
29 """
30
31 @property
32 @abc.abstractmethod
33 def READ(self) -> int: # pylint: disable=C0103
34 """The value of the I/O loop's READ flag; READ/WRITE/ERROR may be used
35 with bitwise operators as expected.
36
37 Implementation note: the implementations can simply replace these
38 READ/WRITE/ERROR properties with class-level attributes
39
40 """
41
42 @property
43 @abc.abstractmethod
44 def WRITE(self) -> int: # pylint: disable=C0103
45 """The value of the I/O loop's WRITE flag; READ/WRITE/ERROR may be used
46 with bitwise operators as expected
47
48 """
49
50 @property
51 @abc.abstractmethod
52 def ERROR(self) -> int: # pylint: disable=C0103
53 """The value of the I/O loop's ERROR flag; READ/WRITE/ERROR may be used
54 with bitwise operators as expected
55
56 """
57
58 @abc.abstractmethod
59 def close(self) -> None:
60 """Release IOLoop's resources.
61
62 the `close()` method is intended to be called by the application or test
63 code only after `start()` returns. After calling `close()`, no other
64 interaction with the closed instance of `IOLoop` should be performed.
65
66 """
67
68 @abc.abstractmethod
69 def start(self) -> None:
70 """Run the I/O loop. It will loop until requested to exit. See `stop()`.
71
72 """
73
74 @abc.abstractmethod
75 def stop(self) -> None:
76 """Request exit from the ioloop. The loop is NOT guaranteed to
77 stop before this method returns.
78
79 To invoke `stop()` safely from a thread other than this IOLoop's thread,
80 call it via `add_callback_threadsafe`; e.g.,
81
82 `ioloop.add_callback(ioloop.stop)`
83
84 """
85
86 @abc.abstractmethod
87 def call_later(self, delay: float, callback: Callable[..., Any]) -> object:
88 """Add the callback to the IOLoop timer to be called after delay seconds
89 from the time of call on best-effort basis. Returns a handle to the
90 timeout.
91
92 :param float delay: The number of seconds to wait to call callback
93 :param callable callback: The callback method
94 :returns: handle to the created timeout that may be passed to
95 `remove_timeout()`
96 :rtype: object
97
98 """
99
100 @abc.abstractmethod
101 def remove_timeout(self, timeout_handle: Any) -> None:
102 """Remove a timeout
103
104 :param timeout_handle: Handle of timeout to remove
105
106 """
107
108 @abc.abstractmethod
109 def add_callback(self, callback: Callable[..., Any]) -> None:
110 """Requests a call to the given function as soon as possible in the
111 context of this IOLoop's thread.
112
113 NOTE: This is the only thread-safe method in IOLoop. All other
114 manipulations of IOLoop must be performed from the IOLoop's thread.
115
116 For example, a thread may request a call to the `stop` method of an
117 ioloop that is running in a different thread via
118 `ioloop.add_callback_threadsafe(ioloop.stop)`
119
120 :param callable callback: The callback method
121
122 """
123
124 @abc.abstractmethod
125 def add_handler(self, fd: int, handler: Callable[[int, int], None],
126 events: int) -> None:
127 """Start watching the given file descriptor for events
128
129 :param int fd: The file descriptor
130 :param callable handler: When requested event(s) occur,
131 `handler(fd, events)` will be called.
132 :param int events: The event mask using READ, WRITE, ERROR.
133
134 """
135
136 @abc.abstractmethod
137 def update_handler(self, fd: int, events: int) -> None:
138 """Changes the events we watch for
139
140 :param int fd: The file descriptor
141 :param int events: The event mask using READ, WRITE, ERROR
142
143 """
144
145 @abc.abstractmethod
146 def remove_handler(self, fd: int) -> None:
147 """Stop watching the given file descriptor for events
148
149 :param int fd: The file descriptor
150
151 """
152
153
154 class SelectorIOServicesAdapter(io_services_utils.SocketConnectionMixin,
155 io_services_utils.StreamingConnectionMixin,
156 nbio_interface.AbstractIOServices,
157 nbio_interface.AbstractFileDescriptorServices):
158 """Implements the
159 :py:class:`.nbio_interface.AbstractIOServices` interface
160 on top of selector-style native loop having the
161 :py:class:`AbstractSelectorIOLoop` interface, such as
162 :py:class:`pika.selection_connection.IOLoop` and :py:class:`tornado.IOLoop`.
163
164 NOTE:
165 :py:class:`.nbio_interface.AbstractFileDescriptorServices`
166 interface is only required by the mixins.
167
168 """
169
170 def __init__(self, native_loop: AbstractSelectorIOLoop):
171 """
172 :param AbstractSelectorIOLoop native_loop: An instance compatible with
173 the `AbstractSelectorIOLoop` interface, but not necessarily derived
174 from it.
175 """
176 self._loop = native_loop
177
178 # Active watchers: maps file descriptors to `_FileDescriptorCallbacks`
179 self._watchers: Dict[int, _FileDescriptorCallbacks] = dict()
180
181 # Native loop-specific event masks of interest
182 self._readable_mask = self._loop.READ
183 # NOTE: tying ERROR to WRITE is particularly handy for Windows, whose
184 # `select.select()` differs from Posix by reporting
185 # connection-establishment failure only through exceptfds (ERROR event),
186 # while the typical application workflow is to wait for the socket to
187 # become writable when waiting for socket connection to be established.
188 self._writable_mask = self._loop.WRITE | self._loop.ERROR
189
190 def get_native_ioloop(self) -> AbstractSelectorIOLoop:
191 """Implement
192 :py:meth:`.nbio_interface.AbstractIOServices.get_native_ioloop()`.
193
194 """
195 return self._loop
196
197 def close(self) -> None:
198 """Implement :py:meth:`.nbio_interface.AbstractIOServices.close()`.
199
200 """
201 self._loop.close()
202
203 def run(self) -> None:
204 """Implement :py:meth:`.nbio_interface.AbstractIOServices.run()`.
205
206 """
207 self._loop.start()
208
209 def stop(self) -> None:
210 """Implement :py:meth:`.nbio_interface.AbstractIOServices.stop()`.
211
212 """
213 self._loop.stop()
214
215 def add_callback_threadsafe(self, callback):
216 """Implement
217 :py:meth:`.nbio_interface.AbstractIOServices.add_callback_threadsafe()`.
218
219 """
220 self._loop.add_callback(callback)
221
222 def call_later(self, delay, callback: Callable[..., None]) -> _TimerHandle:
223 """Implement :py:meth:`.nbio_interface.AbstractIOServices.call_later()`.
224
225 """
226 return _TimerHandle(self._loop.call_later(delay, callback), self._loop)
227
228 def getaddrinfo(self,
229 host: str,
230 port: int,
231 on_done: Callable[..., None],
232 family: int = 0,
233 socktype: int = 0,
234 proto: int = 0,
235 flags: int = 0) -> nbio_interface.AbstractIOReference:
236 """Implement :py:meth:`.nbio_interface.AbstractIOServices.getaddrinfo()`.
237
238 """
239 return _SelectorIOLoopIOHandle(
240 _AddressResolver(native_loop=self._loop,
241 host=host,
242 port=port,
243 family=family,
244 socktype=socktype,
245 proto=proto,
246 flags=flags,
247 on_done=on_done).start())
248
249 def set_reader(self, fd: int, on_readable: Callable[[], None]) -> None:
250 """Implement
251 :py:meth:`.nbio_interface.AbstractFileDescriptorServices.set_reader()`.
252
253 """
254 LOGGER.debug('SelectorIOServicesAdapter.set_reader(%s, %r)', fd,
255 on_readable)
256
257 check_fd_arg(fd)
258 check_callback_arg(on_readable, 'on_readable')
259
260 try:
261 callbacks = self._watchers[fd]
262 except KeyError:
263 self._loop.add_handler(fd, self._on_reader_writer_fd_events,
264 self._readable_mask)
265 self._watchers[fd] = _FileDescriptorCallbacks(reader=on_readable)
266 LOGGER.debug('set_reader(%s, _) added handler Rd', fd)
267 else:
268 if callbacks.reader is None:
269 assert callbacks.writer is not None
270 self._loop.update_handler(
271 fd, self._readable_mask | self._writable_mask)
272 LOGGER.debug('set_reader(%s, _) updated handler RdWr', fd)
273 else:
274 LOGGER.debug('set_reader(%s, _) replacing reader', fd)
275
276 callbacks.reader = on_readable
277
278 def remove_reader(self, fd: int) -> bool:
279 """Implement
280 :py:meth:`.nbio_interface.AbstractFileDescriptorServices.remove_reader()`.
281
282 """
283 LOGGER.debug('SelectorIOServicesAdapter.remove_reader(%s)', fd)
284
285 check_fd_arg(fd)
286
287 try:
288 callbacks = self._watchers[fd]
289 except KeyError:
290 LOGGER.debug('remove_reader(%s) neither was set', fd)
291 return False
292
293 if callbacks.reader is None:
294 assert callbacks.writer is not None
295 LOGGER.debug('remove_reader(%s) reader wasn\'t set Wr', fd)
296 return False
297
298 callbacks.reader = None
299
300 if callbacks.writer is None:
301 del self._watchers[fd]
302 self._loop.remove_handler(fd)
303 LOGGER.debug('remove_reader(%s) removed handler', fd)
304 else:
305 self._loop.update_handler(fd, self._writable_mask)
306 LOGGER.debug('remove_reader(%s) updated handler Wr', fd)
307
308 return True
309
310 def set_writer(self, fd: int, on_writable: Callable[[], None]) -> None:
311 """Implement
312 :py:meth:`.nbio_interface.AbstractFileDescriptorServices.set_writer()`.
313
314 """
315 LOGGER.debug('SelectorIOServicesAdapter.set_writer(%s, %r)', fd,
316 on_writable)
317
318 check_fd_arg(fd)
319 check_callback_arg(on_writable, 'on_writable')
320
321 try:
322 callbacks = self._watchers[fd]
323 except KeyError:
324 self._loop.add_handler(fd, self._on_reader_writer_fd_events,
325 self._writable_mask)
326 self._watchers[fd] = _FileDescriptorCallbacks(writer=on_writable)
327 LOGGER.debug('set_writer(%s, _) added handler Wr', fd)
328 else:
329 if callbacks.writer is None:
330 assert callbacks.reader is not None
331 # NOTE: Set the writer func before setting the mask!
332 # Otherwise a race condition can occur where ioloop tries to
333 # call writer when it is still None.
334 callbacks.writer = on_writable
335 self._loop.update_handler(
336 fd, self._readable_mask | self._writable_mask)
337 LOGGER.debug('set_writer(%s, _) updated handler RdWr', fd)
338 else:
339 LOGGER.debug('set_writer(%s, _) replacing writer', fd)
340 callbacks.writer = on_writable
341
342 def remove_writer(self, fd: int) -> bool:
343 """Implement
344 :py:meth:`.nbio_interface.AbstractFileDescriptorServices.remove_writer()`.
345
346 """
347 LOGGER.debug('SelectorIOServicesAdapter.remove_writer(%s)', fd)
348
349 check_fd_arg(fd)
350
351 try:
352 callbacks = self._watchers[fd]
353 except KeyError:
354 LOGGER.debug('remove_writer(%s) neither was set.', fd)
355 return False
356
357 if callbacks.writer is None:
358 assert callbacks.reader is not None
359 LOGGER.debug('remove_writer(%s) writer wasn\'t set Rd', fd)
360 return False
361
362 callbacks.writer = None
363
364 if callbacks.reader is None:
365 del self._watchers[fd]
366 self._loop.remove_handler(fd)
367 LOGGER.debug('remove_writer(%s) removed handler', fd)
368 else:
369 self._loop.update_handler(fd, self._readable_mask)
370 LOGGER.debug('remove_writer(%s) updated handler Rd', fd)
371
372 return True
373
374 def _on_reader_writer_fd_events(self, fd: int, events: int) -> None:
375 """Handle indicated file descriptor events requested via `set_reader()`
376 and `set_writer()`.
377
378 :param fd: file descriptor
379 :param events: event mask using native loop's READ/WRITE/ERROR. NOTE:
380 depending on the underlying poller mechanism, ERROR may be indicated
381 upon certain file description state even though we don't request it.
382 We ignore ERROR here since `set_reader()`/`set_writer()` don't
383 request for it.
384 """
385 callbacks = self._watchers[fd]
386
387 if events & self._readable_mask and callbacks.reader is None:
388 # NOTE: we check for consistency here ahead of the writer callback
389 # because the writer callback, if any, can change the events being
390 # watched
391 LOGGER.warning(
392 'READ indicated on fd=%s, but reader callback is None; '
393 'events=%s', fd, bin(events))
394
395 if events & self._writable_mask:
396 if callbacks.writer is not None:
397 callbacks.writer()
398 else:
399 LOGGER.warning(
400 'WRITE indicated on fd=%s, but writer callback is None; '
401 'events=%s', fd, bin(events))
402
403 if events & self._readable_mask:
404 if callbacks.reader is not None:
405 callbacks.reader()
406 else:
407 # Reader callback might have been removed in the scope of writer
408 # callback.
409 pass
410
411
412 class _FileDescriptorCallbacks:
413 """Holds reader and writer callbacks for a file descriptor"""
414
415 __slots__ = ('reader', 'writer')
416
417 def __init__(self,
418 reader: Optional[Callable[[], None]] = None,
419 writer: Optional[Callable[[], None]] = None):
420
421 self.reader = reader
422 self.writer = writer
423
424
425 class _TimerHandle(nbio_interface.AbstractTimerReference):
426 """This module's adaptation of `nbio_interface.AbstractTimerReference`.
427
428 """
429
430 def __init__(self, handle: object, loop: AbstractSelectorIOLoop):
431 """
432
433 :param opaque handle: timer handle from the underlying loop
434 implementation that may be passed to its `remove_timeout()` method
435 :param AbstractSelectorIOLoop loop: the I/O loop instance that created
436 the timeout.
437 """
438 self._handle = handle
439 self._loop = loop
440
441 def cancel(self):
442 if self._loop is not None:
443 self._loop.remove_timeout(self._handle)
444 self._handle = None
445 self._loop = None # type: ignore
446
447
448 class _SelectorIOLoopIOHandle(nbio_interface.AbstractIOReference):
449 """This module's adaptation of `nbio_interface.AbstractIOReference`
450
451 """
452
453 def __init__(self, subject: Any) -> None:
454 """
455 :param subject: subject of the reference containing a `cancel()` method
456
457 """
458 self._cancel = subject.cancel
459
460 def cancel(self) -> bool:
461 """Cancel pending operation
462
463 :returns: False if was already done or cancelled; True otherwise
464 :rtype: bool
465
466 """
467 return self._cancel()
468
469
470 class _AddressResolver:
471 """Performs getaddrinfo asynchronously using a thread, then reports result
472 via callback from the given I/O loop.
473
474 NOTE: at this stage, we're using a thread per request, which may prove
475 inefficient and even prohibitive if the app performs many of these
476 operations concurrently.
477 """
478 NOT_STARTED = 0
479 ACTIVE = 1
480 CANCELED = 2
481 COMPLETED = 3
482
483 def __init__(self, native_loop: AbstractSelectorIOLoop, host: str,
484 port: int, family: int, socktype: int, proto: int, flags: int,
485 on_done: Callable[..., None]) -> None:
486 """
487
488 :param AbstractSelectorIOLoop native_loop:
489 :param host: `see socket.getaddrinfo()`
490 :param port: `see socket.getaddrinfo()`
491 :param family: `see socket.getaddrinfo()`
492 :param socktype: `see socket.getaddrinfo()`
493 :param proto: `see socket.getaddrinfo()`
494 :param flags: `see socket.getaddrinfo()`
495 :param on_done: on_done(records|BaseException) callback for reporting
496 result from the given I/O loop. The single arg will be either an
497 exception object (check for `BaseException`) in case of failure or
498 the result returned by `socket.getaddrinfo()`.
499 """
500 check_callback_arg(on_done, 'on_done')
501
502 self._state = self.NOT_STARTED
503 self._result: Any = None
504 self._loop: Optional[AbstractSelectorIOLoop] = native_loop
505 self._host = host
506 self._port = port
507 self._family = family
508 self._socktype = socktype
509 self._proto = proto
510 self._flags = flags
511 self._on_done: Optional[Callable[..., None]] = on_done
512
513 self._mutex = threading.Lock()
514 self._threading_timer: Optional[threading.Timer] = None
515
516 def _cleanup(self) -> None:
517 """Release resources
518
519 """
520 self._loop = None
521 self._threading_timer = None
522 self._on_done = None
523
524 def start(self) -> _SelectorIOLoopIOHandle:
525 """Start asynchronous DNS lookup.
526
527 :rtype: nbio_interface.AbstractIOReference
528
529 """
530 assert self._state == self.NOT_STARTED, self._state
531
532 self._state = self.ACTIVE
533 self._threading_timer = threading.Timer(0, self._resolve)
534 self._threading_timer.start()
535
536 return _SelectorIOLoopIOHandle(self)
537
538 def cancel(self) -> bool:
539 """Cancel the pending resolver
540
541 :returns: False if was already done or cancelled; True otherwise
542 :rtype: bool
543
544 """
545 # Try to cancel, but no guarantees
546 with self._mutex:
547 if self._state == self.ACTIVE:
548 LOGGER.debug('Canceling resolver for %s:%s', self._host,
549 self._port)
550 self._state = self.CANCELED
551
552 # Attempt to cancel, but not guaranteed
553 self._threading_timer.cancel() # type: ignore
554
555 self._cleanup()
556
557 return True
558 else:
559 LOGGER.debug(
560 'Ignoring _AddressResolver cancel request when not ACTIVE; '
561 '(%s:%s); state=%s', self._host, self._port, self._state)
562 return False
563
564 def _resolve(self) -> None:
565 """Call `socket.getaddrinfo()` and return result via user's callback
566 function on the given I/O loop
567
568 """
569 try:
570 result: Any = socket.getaddrinfo(host=self._host,
571 port=self._port,
572 family=self._family,
573 type=self._socktype,
574 proto=self._proto,
575 flags=self._flags)
576 except Exception as exc: # pylint: disable=W0703
577 LOGGER.error('Address resolution failed: %r', exc)
578 result = exc
579
580 self._result = result
581
582 # Schedule result to be returned to user via user's event loop
583 with self._mutex:
584 if self._state == self.ACTIVE:
585 self._loop.add_callback(self._dispatch_result) # type: ignore
586 else:
587 LOGGER.debug(
588 'Asynchronous getaddrinfo cancellation detected; '
589 'in thread; host=%r', self._host)
590
591 def _dispatch_result(self) -> None:
592 """This is called from the user's I/O loop to pass the result to the
593 user via the user's on_done callback
594
595 """
596 if self._state == self.ACTIVE:
597 self._state = self.COMPLETED
598 try:
599 LOGGER.debug(
600 'Invoking asynchronous getaddrinfo() completion callback; '
601 'host=%r', self._host)
602 self._on_done(self._result) # type: ignore
603 finally:
604 self._cleanup()
605 else:
606 LOGGER.debug(
607 'Asynchronous getaddrinfo cancellation detected; '
608 'in I/O loop context; host=%r', self._host)