| 1 |
# |
| 2 |
# Licensed to the Apache Software Foundation (ASF) under one |
| 3 |
# or more contributor license agreements. See the NOTICE file |
| 4 |
# distributed with this work for additional information |
| 5 |
# regarding copyright ownership. The ASF licenses this file |
| 6 |
# to you under the Apache License, Version 2.0 (the |
| 7 |
# "License"); you may not use this file except in compliance |
| 8 |
# with the License. You may obtain a copy of the License at |
| 9 |
# |
| 10 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
# |
| 12 |
# Unless required by applicable law or agreed to in writing, |
| 13 |
# software distributed under the License is distributed on an |
| 14 |
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 |
# KIND, either express or implied. See the License for the |
| 16 |
# specific language governing permissions and limitations |
| 17 |
# under the License. |
| 18 |
# |
| 19 |
|
| 20 |
import heapq |
| 21 |
import json |
| 22 |
import logging |
| 23 |
import re |
| 24 |
import os |
| 25 |
import queue |
| 26 |
from typing import Any, Dict, Iterator, Optional, List, Union, Callable, TYPE_CHECKING, Tuple, Type |
| 27 |
|
| 28 |
try: |
| 29 |
from typing import Literal |
| 30 |
except ImportError: |
| 31 |
# https://www.python.org/dev/peps/pep-0560/#class-getitem |
| 32 |
class GenericMeta(type): |
| 33 |
def __getitem__(self, item): |
| 34 |
pass |
| 35 |
|
| 36 |
class Literal(metaclass=GenericMeta): |
| 37 |
pass |
| 38 |
|
| 39 |
import time |
| 40 |
import traceback |
| 41 |
import uuid |
| 42 |
from functools import total_ordering |
| 43 |
|
| 44 |
from cproton import PN_PYREF, PN_ACCEPTED, PN_EVENT_NONE |
| 45 |
|
| 46 |
from ._common import isstring, unicode2utf8, utf82unicode |
| 47 |
from ._data import Described, symbol, ulong |
| 48 |
from ._delivery import Delivery |
| 49 |
from ._endpoints import Connection, Endpoint, Link, Session, Terminus |
| 50 |
from ._events import Collector, EventType, EventBase, Handler, Event |
| 51 |
from ._exceptions import SSLUnavailable |
| 52 |
from ._handlers import OutgoingMessageHandler, IOHandler |
| 53 |
from ._io import IO |
| 54 |
from ._message import Message |
| 55 |
from ._transport import Transport, SSL, SSLDomain |
| 56 |
from ._url import Url |
| 57 |
from ._selectable import Selectable |
| 58 |
|
| 59 |
if TYPE_CHECKING: |
| 60 |
from ._endpoints import Receiver, Sender |
| 61 |
from ._data import PythonAMQPData |
| 62 |
from ._handlers import TransactionHandler |
| 63 |
from socket import socket |
| 64 |
from types import TracebackType |
| 65 |
from uuid import UUID |
| 66 |
|
| 67 |
|
| 68 |
_logger = logging.getLogger("proton") |
| 69 |
|
| 70 |
|
| 71 |
def _generate_uuid() -> 'UUID': |
| 72 |
return uuid.uuid4() |
| 73 |
|
| 74 |
|
| 75 |
def _now() -> float: |
| 76 |
return time.time() |
| 77 |
|
| 78 |
|
| 79 |
@total_ordering |
| 80 |
class Task(object): |
| 81 |
|
| 82 |
def __init__(self, reactor: 'Container', deadline: float, handler: Handler) -> None: |
| 83 |
self._deadline = deadline |
| 84 |
self._handler = handler |
| 85 |
self._reactor = reactor |
| 86 |
self._cancelled = False |
| 87 |
|
| 88 |
def __lt__(self, rhs: 'Task') -> bool: |
| 89 |
return self._deadline < rhs._deadline |
| 90 |
|
| 91 |
def cancel(self) -> None: |
| 92 |
self._cancelled = True |
| 93 |
|
| 94 |
@property |
| 95 |
def handler(self) -> Handler: |
| 96 |
return self._handler |
| 97 |
|
| 98 |
@property |
| 99 |
def container(self) -> 'Container': |
| 100 |
return self._reactor |
| 101 |
|
| 102 |
|
| 103 |
class TimerSelectable(Selectable): |
| 104 |
|
| 105 |
def __init__(self, reactor: 'Container') -> None: |
| 106 |
super(TimerSelectable, self).__init__(None, reactor) |
| 107 |
|
| 108 |
def readable(self) -> None: |
| 109 |
pass |
| 110 |
|
| 111 |
def writable(self) -> None: |
| 112 |
pass |
| 113 |
|
| 114 |
def expired(self) -> None: |
| 115 |
self._reactor.timer_tick() |
| 116 |
self.deadline = self._reactor.timer_deadline |
| 117 |
self.update() |
| 118 |
|
| 119 |
|
| 120 |
class Reactor(object): |
| 121 |
|
| 122 |
def __init__(self, *handlers, **kwargs) -> None: |
| 123 |
self._previous = PN_EVENT_NONE |
| 124 |
self._timeout = 0 |
| 125 |
self.mark() |
| 126 |
self._yield = False |
| 127 |
self._stop = False |
| 128 |
self._collector = Collector() |
| 129 |
self._selectable = None |
| 130 |
self._selectables = 0 |
| 131 |
self._global_handler = IOHandler() |
| 132 |
self._handler = Handler() |
| 133 |
self._timerheap = [] |
| 134 |
self._timers = 0 |
| 135 |
self.errors: List[Tuple[Type[BaseException], BaseException, 'TracebackType']] = [] |
| 136 |
for h in handlers: |
| 137 |
self.handler.add(h, on_error=self.on_error) |
| 138 |
|
| 139 |
def on_error(self, info: Tuple[Type[BaseException], BaseException, 'TracebackType']) -> None: |
| 140 |
self.errors.append(info) |
| 141 |
self.yield_() |
| 142 |
|
| 143 |
# TODO: need to make this actually return a proxy which catches exceptions and calls |
| 144 |
# on error. |
| 145 |
# [Or arrange another way to deal with exceptions thrown by handlers] |
| 146 |
def _make_handler(self, handler: Handler) -> Handler: |
| 147 |
""" |
| 148 |
Return a proxy handler that dispatches to the provided handler. |
| 149 |
|
| 150 |
If handler throws an exception then on_error is called with info |
| 151 |
""" |
| 152 |
return handler |
| 153 |
|
| 154 |
@property |
| 155 |
def global_handler(self) -> Handler: |
| 156 |
return self._global_handler |
| 157 |
|
| 158 |
@global_handler.setter |
| 159 |
def global_handler(self, handler: Handler) -> None: |
| 160 |
self._global_handler = self._make_handler(handler) |
| 161 |
|
| 162 |
@property |
| 163 |
def timeout(self) -> float: |
| 164 |
return self._timeout |
| 165 |
|
| 166 |
@timeout.setter |
| 167 |
def timeout(self, secs: float) -> None: |
| 168 |
self._timeout = secs |
| 169 |
|
| 170 |
def yield_(self) -> None: |
| 171 |
self._yield = True |
| 172 |
|
| 173 |
def mark(self) -> float: |
| 174 |
""" This sets the reactor now instant to the current time """ |
| 175 |
self._now = _now() |
| 176 |
return self._now |
| 177 |
|
| 178 |
@property |
| 179 |
def now(self) -> float: |
| 180 |
return self._now |
| 181 |
|
| 182 |
@property |
| 183 |
def handler(self) -> Handler: |
| 184 |
return self._handler |
| 185 |
|
| 186 |
@handler.setter |
| 187 |
def handler(self, handler: Handler) -> None: |
| 188 |
self._handler = self._make_handler(handler) |
| 189 |
|
| 190 |
def run(self) -> None: |
| 191 |
""" |
| 192 |
Start the processing of events and messages for this container. |
| 193 |
""" |
| 194 |
# TODO: Why do we timeout like this? |
| 195 |
self.timeout = 3.14159265359 |
| 196 |
self.start() |
| 197 |
while self.process(): |
| 198 |
pass |
| 199 |
self.stop() |
| 200 |
self.process() |
| 201 |
# TODO: This isn't correct if we ever run again |
| 202 |
self._global_handler = None |
| 203 |
self._handler = None |
| 204 |
|
| 205 |
# Cross thread reactor wakeup |
| 206 |
def wakeup(self) -> None: |
| 207 |
# TODO: Do this with pipe and write? |
| 208 |
# os.write(self._wakeup[1], "x", 1); |
| 209 |
pass |
| 210 |
|
| 211 |
def start(self) -> None: |
| 212 |
self.push_event(self, Event.REACTOR_INIT) |
| 213 |
self._selectable = TimerSelectable(self) |
| 214 |
self._selectable.deadline = self.timer_deadline |
| 215 |
# TODO set up fd to read for wakeups - but problematic on windows |
| 216 |
# self._selectable.fileno(self._wakeup[0]) |
| 217 |
# self._selectable.reading = True |
| 218 |
self.update(self._selectable) |
| 219 |
|
| 220 |
@property |
| 221 |
def quiesced(self) -> bool: |
| 222 |
event = self._collector.peek() |
| 223 |
if not event: |
| 224 |
return True |
| 225 |
if self._collector.more(): |
| 226 |
return False |
| 227 |
return event.type is Event.REACTOR_QUIESCED |
| 228 |
|
| 229 |
def _check_errors(self) -> None: |
| 230 |
""" This """ |
| 231 |
if self.errors: |
| 232 |
for exc, value, tb in self.errors[:-1]: |
| 233 |
traceback.print_exception(exc, value, tb) |
| 234 |
exc, value, tb = self.errors[-1] |
| 235 |
if value is None: |
| 236 |
value = exc() |
| 237 |
if tb is None: |
| 238 |
raise value |
| 239 |
else: |
| 240 |
raise value.with_traceback(tb) |
| 241 |
|
| 242 |
def process(self) -> bool: |
| 243 |
# result = pn_reactor_process(self._impl) |
| 244 |
# self._check_errors() |
| 245 |
# return result |
| 246 |
self.mark() |
| 247 |
previous = PN_EVENT_NONE |
| 248 |
while True: |
| 249 |
if self._yield: |
| 250 |
self._yield = False |
| 251 |
_logger.debug('%s Yielding', self) |
| 252 |
return True |
| 253 |
event = self._collector.peek() |
| 254 |
if event: |
| 255 |
_logger.debug('%s recvd Event: %r', self, event) |
| 256 |
type = event.type |
| 257 |
|
| 258 |
# regular handler |
| 259 |
handler = event.handler or self._handler |
| 260 |
event.dispatch(handler) |
| 261 |
|
| 262 |
event.dispatch(self._global_handler) |
| 263 |
|
| 264 |
previous = type |
| 265 |
self._previous = type |
| 266 |
self._collector.pop() |
| 267 |
elif not self._stop and (self._timers > 0 or self._selectables > 1): |
| 268 |
if previous is not Event.REACTOR_QUIESCED and self._previous is not Event.REACTOR_FINAL: |
| 269 |
self.push_event(self, Event.REACTOR_QUIESCED) |
| 270 |
self.yield_() |
| 271 |
else: |
| 272 |
if self._selectable: |
| 273 |
self._selectable.terminate() |
| 274 |
self._selectable.update() |
| 275 |
self._selectable = None |
| 276 |
else: |
| 277 |
if self._previous is not Event.REACTOR_FINAL: |
| 278 |
self.push_event(self, Event.REACTOR_FINAL) |
| 279 |
_logger.debug('%s Stopping', self) |
| 280 |
return False |
| 281 |
|
| 282 |
def stop(self) -> None: |
| 283 |
self._stop = True |
| 284 |
self._check_errors() |
| 285 |
|
| 286 |
def stop_events(self) -> None: |
| 287 |
self._collector.release() |
| 288 |
|
| 289 |
def schedule(self, delay: Union[float, int], handler: Handler) -> Task: |
| 290 |
""" |
| 291 |
Schedule a task to run on this container after a given delay, |
| 292 |
and using the supplied handler. |
| 293 |
|
| 294 |
:param delay: |
| 295 |
:param handler: |
| 296 |
""" |
| 297 |
himpl = self._make_handler(handler) |
| 298 |
task = Task(self, self._now + delay, himpl) |
| 299 |
heapq.heappush(self._timerheap, task) |
| 300 |
self._timers += 1 |
| 301 |
deadline = self._timerheap[0]._deadline |
| 302 |
if self._selectable: |
| 303 |
self._selectable.deadline = deadline |
| 304 |
self.update(self._selectable) |
| 305 |
return task |
| 306 |
|
| 307 |
def timer_tick(self) -> None: |
| 308 |
while self._timers > 0: |
| 309 |
t = self._timerheap[0] |
| 310 |
if t._cancelled: |
| 311 |
heapq.heappop(self._timerheap) |
| 312 |
self._timers -= 1 |
| 313 |
elif t._deadline > self._now: |
| 314 |
return |
| 315 |
else: |
| 316 |
heapq.heappop(self._timerheap) |
| 317 |
self._timers -= 1 |
| 318 |
self.push_event(t, Event.TIMER_TASK) |
| 319 |
|
| 320 |
@property |
| 321 |
def timer_deadline(self) -> Optional[float]: |
| 322 |
while self._timers > 0: |
| 323 |
t = self._timerheap[0] |
| 324 |
if t._cancelled: |
| 325 |
heapq.heappop(self._timerheap) |
| 326 |
self._timers -= 1 |
| 327 |
else: |
| 328 |
return t._deadline |
| 329 |
return None |
| 330 |
|
| 331 |
def acceptor( |
| 332 |
self, |
| 333 |
host: str, |
| 334 |
port: Union[str, Url.Port], |
| 335 |
handler: Optional[Handler] = None, |
| 336 |
) -> 'Acceptor': |
| 337 |
impl = self._make_handler(handler) |
| 338 |
a = Acceptor(self, unicode2utf8(host), int(port), impl) |
| 339 |
if a: |
| 340 |
return a |
| 341 |
else: |
| 342 |
raise IOError("%s (%s:%s)" % (str(self.errors), host, port)) |
| 343 |
|
| 344 |
def connection(self, handler: Optional[Handler] = None) -> Connection: |
| 345 |
"""Deprecated: use connection_to_host() instead |
| 346 |
""" |
| 347 |
impl = self._make_handler(handler) |
| 348 |
result = Connection() |
| 349 |
if impl: |
| 350 |
result.handler = impl |
| 351 |
result._reactor = self |
| 352 |
result.collect(self._collector) |
| 353 |
return result |
| 354 |
|
| 355 |
def connection_to_host(self, host, port, handler: Optional[Handler] = None) -> Connection: |
| 356 |
"""Create an outgoing Connection that will be managed by the reactor. |
| 357 |
The reactor's pn_iohandler will create a socket connection to the host |
| 358 |
once the connection is opened. |
| 359 |
""" |
| 360 |
conn = self.connection(handler) |
| 361 |
self.set_connection_host(conn, host, port) |
| 362 |
return conn |
| 363 |
|
| 364 |
def set_connection_host(self, connection: Connection, host, port) -> None: |
| 365 |
"""Change the address used by the connection. The address is |
| 366 |
used by the reactor's iohandler to create an outgoing socket |
| 367 |
connection. This must be set prior to opening the connection. |
| 368 |
""" |
| 369 |
connection.set_address(host, port) |
| 370 |
|
| 371 |
def get_connection_address(self, connection: Connection) -> str: |
| 372 |
"""*Deprecated* in favor of the property proton.Connection.connected_address. |
| 373 |
This may be used to retrieve the remote peer address. |
| 374 |
:return: string containing the address in URL format or None if no |
| 375 |
address is available. Use the proton.Url class to create a Url object |
| 376 |
from the returned value. |
| 377 |
""" |
| 378 |
return connection.connected_address |
| 379 |
|
| 380 |
def selectable( |
| 381 |
self, |
| 382 |
handler: Optional[Union['Acceptor', 'EventInjector']] = None, |
| 383 |
delegate: Optional['socket'] = None |
| 384 |
) -> Selectable: |
| 385 |
""" |
| 386 |
NO IDEA! |
| 387 |
|
| 388 |
:param handler: no idea |
| 389 |
:type handler: ? |
| 390 |
:param delegate: no idea |
| 391 |
:type delegate: ? |
| 392 |
""" |
| 393 |
if delegate is None: |
| 394 |
delegate = handler |
| 395 |
result = Selectable(delegate, self) |
| 396 |
result.handler = handler |
| 397 |
return result |
| 398 |
|
| 399 |
def update(self, selectable: Selectable) -> None: |
| 400 |
selectable.update() |
| 401 |
|
| 402 |
def push_event( |
| 403 |
self, |
| 404 |
obj: Union['Reactor', Task, 'Container', Selectable], |
| 405 |
etype: EventType |
| 406 |
) -> None: |
| 407 |
self._collector.put(obj, etype) |
| 408 |
|
| 409 |
|
| 410 |
class EventInjector(object): |
| 411 |
""" |
| 412 |
Can be added to a :class:`Container` to allow events to be triggered by an |
| 413 |
external thread but handled on the event thread associated with |
| 414 |
the container. An instance of this class can be passed to the |
| 415 |
:meth:`Container.selectable` method in order to activate |
| 416 |
it. :meth:`close` should be called when it is no longer |
| 417 |
needed, to allow the event loop to end if needed. |
| 418 |
""" |
| 419 |
|
| 420 |
def __init__(self) -> None: |
| 421 |
self.queue = queue.Queue() |
| 422 |
self.pipe = os.pipe() |
| 423 |
self._transport = None |
| 424 |
self._closed = False |
| 425 |
|
| 426 |
def trigger(self, event: 'ApplicationEvent') -> None: |
| 427 |
""" |
| 428 |
Request that the given event be dispatched on the event thread |
| 429 |
of the container to which this EventInjector was added. |
| 430 |
|
| 431 |
:param event: Event to be injected |
| 432 |
:type event: :class:`proton.Event`, :class:`ApplicationEvent` |
| 433 |
""" |
| 434 |
self.queue.put(event) |
| 435 |
os.write(self.pipe[1], b"!") |
| 436 |
|
| 437 |
def close(self) -> None: |
| 438 |
""" |
| 439 |
Request that this EventInjector be closed. Existing events |
| 440 |
will be dispatched on the container's event dispatch thread, |
| 441 |
then this will be removed from the set of interest. |
| 442 |
""" |
| 443 |
self._closed = True |
| 444 |
os.write(self.pipe[1], b"!") |
| 445 |
|
| 446 |
def fileno(self) -> int: |
| 447 |
return self.pipe[0] |
| 448 |
|
| 449 |
def on_selectable_init(self, event: Event) -> None: |
| 450 |
sel = event.context |
| 451 |
# sel.fileno(self.fileno()) |
| 452 |
sel.reading = True |
| 453 |
sel.update() |
| 454 |
|
| 455 |
def on_selectable_readable(self, event: Event) -> None: |
| 456 |
s = event.context |
| 457 |
os.read(self.pipe[0], 512) |
| 458 |
while not self.queue.empty(): |
| 459 |
requested = self.queue.get() |
| 460 |
s.push_event(requested.context, requested.type) |
| 461 |
if self._closed: |
| 462 |
s.terminate() |
| 463 |
s.update() |
| 464 |
|
| 465 |
|
| 466 |
class ApplicationEvent(EventBase): |
| 467 |
""" |
| 468 |
Application defined event, which can optionally be associated with |
| 469 |
an engine object and or an arbitrary subject. This produces |
| 470 |
extended event types - see :class:`proton.EventType` for details. |
| 471 |
|
| 472 |
:param typename: Event type name |
| 473 |
:param connection: Associates this event with a connection. |
| 474 |
:param session: Associates this event with a session. |
| 475 |
:param link: Associate this event with a link. |
| 476 |
:param delivery: Associate this event with a delivery. |
| 477 |
:param subject: Associate this event with an arbitrary object |
| 478 |
""" |
| 479 |
|
| 480 |
TYPES = {} |
| 481 |
|
| 482 |
def __init__( |
| 483 |
self, |
| 484 |
typename: str, |
| 485 |
connection: Optional[Connection] = None, |
| 486 |
session: Optional[Session] = None, |
| 487 |
link: Optional[Link] = None, |
| 488 |
delivery: Optional[Delivery] = None, |
| 489 |
subject: Any = None |
| 490 |
) -> None: |
| 491 |
if isinstance(typename, EventType): |
| 492 |
eventtype = typename |
| 493 |
else: |
| 494 |
try: |
| 495 |
eventtype = self.TYPES[typename] |
| 496 |
except KeyError: |
| 497 |
eventtype = EventType(typename) |
| 498 |
self.TYPES[typename] = eventtype |
| 499 |
super(ApplicationEvent, self).__init__(eventtype) |
| 500 |
self.clazz = PN_PYREF |
| 501 |
self.connection = connection |
| 502 |
self.session = session |
| 503 |
self.link = link |
| 504 |
self.delivery = delivery |
| 505 |
if self.delivery: |
| 506 |
self.link = self.delivery.link |
| 507 |
if self.link: |
| 508 |
self.session = self.link.session |
| 509 |
if self.session: |
| 510 |
self.connection = self.session.connection |
| 511 |
self.subject = subject |
| 512 |
|
| 513 |
@property |
| 514 |
def context(self) -> 'ApplicationEvent': |
| 515 |
""" |
| 516 |
A reference to this event. |
| 517 |
""" |
| 518 |
return self |
| 519 |
|
| 520 |
def __repr__(self) -> str: |
| 521 |
objects = [self.connection, self.session, self.link, self.delivery, self.subject] |
| 522 |
return "%s(%s)" % (self.type, ", ".join([str(o) for o in objects if o is not None])) |
| 523 |
|
| 524 |
|
| 525 |
class Transaction(object): |
| 526 |
""" |
| 527 |
Tracks the state of an AMQP 1.0 local transaction. In typical usage, this |
| 528 |
object is not created directly, but is obtained through the event returned |
| 529 |
by :meth:`proton.handlers.TransactionHandler.on_transaction_declared` after |
| 530 |
a call to :meth:`proton.reactor.Container.declare_transaction`. |
| 531 |
|
| 532 |
To send messages under this transaction, use :meth:`send`. |
| 533 |
|
| 534 |
To receive messages under this transaction, call :meth:`accept` once the |
| 535 |
message is received (typically from the |
| 536 |
:meth:`proton.handlers.MessagingHandler.on_message` callback). |
| 537 |
|
| 538 |
To discharge the transaction, call either :meth:`commit` |
| 539 |
(for a successful transaction), or :meth:`abort` (for a failed transaction). |
| 540 |
""" |
| 541 |
|
| 542 |
def __init__( |
| 543 |
self, |
| 544 |
txn_ctrl: 'Sender', |
| 545 |
handler: 'TransactionHandler', |
| 546 |
settle_before_discharge: bool = False, |
| 547 |
) -> None: |
| 548 |
self.txn_ctrl = txn_ctrl |
| 549 |
self.handler = handler |
| 550 |
self.id = None |
| 551 |
self._declare = None |
| 552 |
self._discharge = None |
| 553 |
self.failed = False |
| 554 |
self._pending = [] |
| 555 |
self.settle_before_discharge = settle_before_discharge |
| 556 |
self.declare() |
| 557 |
|
| 558 |
def commit(self) -> None: |
| 559 |
""" |
| 560 |
Commit this transaction. Closes the transaction as a success. |
| 561 |
""" |
| 562 |
self.discharge(False) |
| 563 |
|
| 564 |
def abort(self) -> None: |
| 565 |
""" |
| 566 |
Abort or roll back this transaction. Closes the transaction as a failure, |
| 567 |
and reverses, or rolls back all actions (sent and received messages) |
| 568 |
performed under this transaction. |
| 569 |
""" |
| 570 |
self.discharge(True) |
| 571 |
|
| 572 |
def declare(self) -> None: |
| 573 |
self._declare = self._send_ctrl(symbol(u'amqp:declare:list'), [None]) |
| 574 |
|
| 575 |
def discharge(self, failed: bool) -> None: |
| 576 |
self.failed = failed |
| 577 |
self._discharge = self._send_ctrl(symbol(u'amqp:discharge:list'), [self.id, failed]) |
| 578 |
|
| 579 |
def _send_ctrl(self, descriptor: 'PythonAMQPData', value: 'PythonAMQPData') -> Delivery: |
| 580 |
delivery = self.txn_ctrl.send(Message(body=Described(descriptor, value))) |
| 581 |
delivery.transaction = self |
| 582 |
return delivery |
| 583 |
|
| 584 |
def send( |
| 585 |
self, |
| 586 |
sender: 'Sender', |
| 587 |
msg: Message, |
| 588 |
tag: Optional[str] = None, |
| 589 |
) -> Delivery: |
| 590 |
""" |
| 591 |
Send a message under this transaction. |
| 592 |
|
| 593 |
:param sender: Link over which to send the message. |
| 594 |
:param msg: Message to be sent under this transaction. |
| 595 |
:param tag: The delivery tag |
| 596 |
:return: Delivery object for this message. |
| 597 |
""" |
| 598 |
dlv = sender.send(msg, tag=tag) |
| 599 |
dlv.local.data = [self.id] |
| 600 |
dlv.update(0x34) |
| 601 |
return dlv |
| 602 |
|
| 603 |
def accept(self, delivery: Delivery) -> None: |
| 604 |
""" |
| 605 |
Accept a received message under this transaction. |
| 606 |
|
| 607 |
:param delivery: Delivery object for the received message. |
| 608 |
""" |
| 609 |
self.update(delivery, PN_ACCEPTED) |
| 610 |
if self.settle_before_discharge: |
| 611 |
delivery.settle() |
| 612 |
else: |
| 613 |
self._pending.append(delivery) |
| 614 |
|
| 615 |
def update(self, delivery: Delivery, state: Optional[ulong] = None) -> None: |
| 616 |
if state: |
| 617 |
delivery.local.data = [self.id, Described(ulong(state), [])] |
| 618 |
delivery.update(0x34) |
| 619 |
|
| 620 |
def _release_pending(self): |
| 621 |
for d in self._pending: |
| 622 |
d.update(Delivery.RELEASED) |
| 623 |
d.settle() |
| 624 |
self._clear_pending() |
| 625 |
|
| 626 |
def _clear_pending(self): |
| 627 |
self._pending = [] |
| 628 |
|
| 629 |
def handle_outcome(self, event): |
| 630 |
if event.delivery == self._declare: |
| 631 |
if event.delivery.remote.data: |
| 632 |
self.id = event.delivery.remote.data[0] |
| 633 |
self.handler.on_transaction_declared(event) |
| 634 |
elif event.delivery.remote_state == Delivery.REJECTED: |
| 635 |
self.handler.on_transaction_declare_failed(event) |
| 636 |
else: |
| 637 |
_logger.warning("Unexpected outcome for declare: %s" % event.delivery.remote_state) |
| 638 |
self.handler.on_transaction_declare_failed(event) |
| 639 |
elif event.delivery == self._discharge: |
| 640 |
if event.delivery.remote_state == Delivery.REJECTED: |
| 641 |
if not self.failed: |
| 642 |
self.handler.on_transaction_commit_failed(event) |
| 643 |
self._release_pending() # make this optional? |
| 644 |
else: |
| 645 |
if self.failed: |
| 646 |
self.handler.on_transaction_aborted(event) |
| 647 |
self._release_pending() |
| 648 |
else: |
| 649 |
self.handler.on_transaction_committed(event) |
| 650 |
self._clear_pending() |
| 651 |
|
| 652 |
|
| 653 |
class LinkOption(object): |
| 654 |
""" |
| 655 |
Abstract interface for link configuration options |
| 656 |
""" |
| 657 |
|
| 658 |
def apply(self, link: Link) -> None: |
| 659 |
""" |
| 660 |
Subclasses will implement any configuration logic in this |
| 661 |
method |
| 662 |
""" |
| 663 |
pass |
| 664 |
|
| 665 |
def test(self, link: Link) -> bool: |
| 666 |
""" |
| 667 |
Subclasses can override this to selectively apply an option |
| 668 |
e.g. based on some link criteria |
| 669 |
""" |
| 670 |
return True |
| 671 |
|
| 672 |
|
| 673 |
class AtMostOnce(LinkOption): |
| 674 |
""" |
| 675 |
Set at-most-once delivery semantics for message delivery. This is achieved by |
| 676 |
setting the sender link settle mode to :const:`proton.Link.SND_SETTLED` |
| 677 |
(ie pre-settled). |
| 678 |
""" |
| 679 |
|
| 680 |
def apply(self, link: Link) -> None: |
| 681 |
""" |
| 682 |
Set the at-most-once delivery semantics on the link. |
| 683 |
|
| 684 |
:param link: The link on which this option is to be applied. |
| 685 |
:type link: :class:`proton.Link` |
| 686 |
""" |
| 687 |
link.snd_settle_mode = Link.SND_SETTLED |
| 688 |
|
| 689 |
|
| 690 |
class AtLeastOnce(LinkOption): |
| 691 |
""" |
| 692 |
Set at-least-once delivery semantics for message delivery. This is achieved |
| 693 |
by setting the sender link settle mode to :const:`proton.Link.SND_UNSETTLED` |
| 694 |
and the receiver link settle mode to :const:`proton.Link.RCV_FIRST`. This |
| 695 |
forces the receiver to settle all messages once they are successfully received. |
| 696 |
""" |
| 697 |
|
| 698 |
def apply(self, link: Link) -> None: |
| 699 |
""" |
| 700 |
Set the at-least-once delivery semantics on the link. |
| 701 |
|
| 702 |
:param link: The link on which this option is to be applied. |
| 703 |
:type link: :class:`proton.Link` |
| 704 |
""" |
| 705 |
link.snd_settle_mode = Link.SND_UNSETTLED |
| 706 |
link.rcv_settle_mode = Link.RCV_FIRST |
| 707 |
|
| 708 |
|
| 709 |
class SenderOption(LinkOption): |
| 710 |
""" |
| 711 |
Abstract class for sender options. |
| 712 |
""" |
| 713 |
|
| 714 |
def apply(self, sender: 'Sender') -> None: |
| 715 |
""" |
| 716 |
Set the option on the sender. |
| 717 |
|
| 718 |
:param sender: The sender on which this option is to be applied. |
| 719 |
""" |
| 720 |
pass |
| 721 |
|
| 722 |
def test(self, link: Link) -> bool: |
| 723 |
return link.is_sender |
| 724 |
|
| 725 |
|
| 726 |
class ReceiverOption(LinkOption): |
| 727 |
""" |
| 728 |
Abstract class for receiver options |
| 729 |
""" |
| 730 |
|
| 731 |
def apply(self, receiver: 'Receiver') -> None: |
| 732 |
""" |
| 733 |
Set the option on the receiver. |
| 734 |
|
| 735 |
:param receiver: The receiver on which this option is to be applied. |
| 736 |
""" |
| 737 |
pass |
| 738 |
|
| 739 |
def test(self, link: Link) -> bool: |
| 740 |
return link.is_receiver |
| 741 |
|
| 742 |
|
| 743 |
class DynamicNodeProperties(LinkOption): |
| 744 |
""" |
| 745 |
Allows a map of link properties to be set on a link. The |
| 746 |
keys may be :class:`proton.symbol` or strings (in which case |
| 747 |
they will be converted to symbols before being applied). |
| 748 |
|
| 749 |
:param props: A map of link options to be applied to a link. |
| 750 |
""" |
| 751 |
|
| 752 |
def __init__(self, props: dict = {}) -> None: |
| 753 |
self.properties = {} |
| 754 |
for k in props: |
| 755 |
if isinstance(k, symbol): |
| 756 |
self.properties[k] = props[k] |
| 757 |
else: |
| 758 |
self.properties[symbol(k)] = props[k] |
| 759 |
|
| 760 |
def apply(self, link: Link) -> None: |
| 761 |
""" |
| 762 |
Set the map of properties on the specified link. |
| 763 |
|
| 764 |
:param link: The link on which this property map is to be set. |
| 765 |
""" |
| 766 |
if link.is_receiver: |
| 767 |
link.source.properties.put_dict(self.properties) |
| 768 |
else: |
| 769 |
link.target.properties.put_dict(self.properties) |
| 770 |
|
| 771 |
|
| 772 |
class Filter(ReceiverOption): |
| 773 |
""" |
| 774 |
Receiver option which allows incoming messages to be filtered. |
| 775 |
|
| 776 |
:param filter_set: A map of filters with :class:`proton.symbol` keys |
| 777 |
containing the filter name, and the value a filter string. |
| 778 |
""" |
| 779 |
|
| 780 |
def __init__(self, filter_set: Dict[symbol, Described] = {}) -> None: |
| 781 |
self.filter_set = filter_set |
| 782 |
|
| 783 |
def apply(self, receiver: 'Receiver') -> None: |
| 784 |
""" |
| 785 |
Set the filter on the specified receiver. |
| 786 |
|
| 787 |
:param receiver: The receiver on which this filter is to be applied. |
| 788 |
""" |
| 789 |
receiver.source.filter.put_dict(self.filter_set) |
| 790 |
|
| 791 |
|
| 792 |
class Selector(Filter): |
| 793 |
""" |
| 794 |
Configures a receiver with a message selector filter |
| 795 |
|
| 796 |
:param value: Selector filter string |
| 797 |
:param name: Name of the selector, defaults to ``"selector"``. |
| 798 |
""" |
| 799 |
|
| 800 |
def __init__(self, value: Union[bytes, str], name: str = 'selector') -> None: |
| 801 |
super(Selector, self).__init__({symbol(name): Described( |
| 802 |
symbol('apache.org:selector-filter:string'), utf82unicode(value))}) |
| 803 |
|
| 804 |
|
| 805 |
class DurableSubscription(ReceiverOption): |
| 806 |
""" |
| 807 |
Receiver option which sets both the configuration and delivery state |
| 808 |
to durable. This is achieved by setting the receiver's source durability |
| 809 |
to :const:`proton.Terminus.DELIVERIES` and the source expiry policy to |
| 810 |
:const:`proton.Terminus.EXPIRE_NEVER`. |
| 811 |
""" |
| 812 |
|
| 813 |
def apply(self, receiver: 'Receiver'): |
| 814 |
""" |
| 815 |
Set durability on the specified receiver. |
| 816 |
|
| 817 |
:param receiver: The receiver on which durability is to be set. |
| 818 |
""" |
| 819 |
receiver.source.durability = Terminus.DELIVERIES |
| 820 |
receiver.source.expiry_policy = Terminus.EXPIRE_NEVER |
| 821 |
|
| 822 |
|
| 823 |
class Move(ReceiverOption): |
| 824 |
""" |
| 825 |
Receiver option which moves messages to the receiver (rather than copying). |
| 826 |
This has the effect of distributing the incoming messages between the |
| 827 |
receivers. This is achieved by setting the receiver source distribution |
| 828 |
mode to :const:`proton.Terminus.DIST_MODE_MOVE`. |
| 829 |
""" |
| 830 |
|
| 831 |
def apply(self, receiver: 'Receiver'): |
| 832 |
""" |
| 833 |
Set message move semantics on the specified receiver. |
| 834 |
|
| 835 |
:param receiver: The receiver on which message move semantics is to be set. |
| 836 |
""" |
| 837 |
receiver.source.distribution_mode = Terminus.DIST_MODE_MOVE |
| 838 |
|
| 839 |
|
| 840 |
class Copy(ReceiverOption): |
| 841 |
""" |
| 842 |
Receiver option which copies messages to the receiver. This ensures that all |
| 843 |
receivers receive all incoming messages, no matter how many receivers there |
| 844 |
are. This is achieved by setting the receiver source distribution mode to |
| 845 |
:const:`proton.Terminus.DIST_MODE_COPY`. |
| 846 |
""" |
| 847 |
|
| 848 |
def apply(self, receiver: 'Receiver'): |
| 849 |
""" |
| 850 |
Set message copy semantics on the specified receiver. |
| 851 |
|
| 852 |
:param receiver: The receiver on which message copy semantics is to be set. |
| 853 |
""" |
| 854 |
receiver.source.distribution_mode = Terminus.DIST_MODE_COPY |
| 855 |
|
| 856 |
|
| 857 |
def _apply_link_options( |
| 858 |
options: Optional[Union[LinkOption, List[LinkOption]]], |
| 859 |
link: Union['Sender', 'Receiver'] |
| 860 |
) -> None: |
| 861 |
if options: |
| 862 |
if isinstance(options, list): |
| 863 |
for o in options: |
| 864 |
if o.test(link): |
| 865 |
o.apply(link) |
| 866 |
else: |
| 867 |
if options.test(link): |
| 868 |
options.apply(link) |
| 869 |
|
| 870 |
|
| 871 |
def _create_session(connection: Connection, handler: Optional[Handler] = None) -> Session: |
| 872 |
session = connection.session() |
| 873 |
session.open() |
| 874 |
return session |
| 875 |
|
| 876 |
|
| 877 |
def _get_attr(target: Any, name: str) -> Optional[Any]: |
| 878 |
if hasattr(target, name): |
| 879 |
return getattr(target, name) |
| 880 |
else: |
| 881 |
return None |
| 882 |
|
| 883 |
|
| 884 |
class SessionPerConnection(object): |
| 885 |
def __init__(self) -> None: |
| 886 |
self._default_session = None |
| 887 |
|
| 888 |
def session(self, connection: Connection) -> Session: |
| 889 |
if not self._default_session: |
| 890 |
self._default_session = _create_session(connection) |
| 891 |
return self._default_session |
| 892 |
|
| 893 |
|
| 894 |
class GlobalOverrides(Handler): |
| 895 |
""" |
| 896 |
Internal handler that triggers the necessary socket connect for an |
| 897 |
opened connection. |
| 898 |
""" |
| 899 |
|
| 900 |
def __init__(self, base: IOHandler) -> None: |
| 901 |
self.base = base |
| 902 |
|
| 903 |
def on_unhandled(self, name: str, event: Event) -> None: |
| 904 |
if not self._override(event): |
| 905 |
event.dispatch(self.base) |
| 906 |
|
| 907 |
def _override(self, event: Event) -> Optional[bool]: |
| 908 |
conn = event.connection |
| 909 |
return conn and hasattr(conn, '_overrides') and event.dispatch(conn._overrides) |
| 910 |
|
| 911 |
|
| 912 |
class Acceptor(Handler): |
| 913 |
|
| 914 |
def __init__(self, reactor: 'Container', host: str, port: int, handler: Optional[Handler] = None) -> None: |
| 915 |
self._ssl_domain = None |
| 916 |
self._reactor = reactor |
| 917 |
self._handler = handler |
| 918 |
sock = IO.listen(host, port) |
| 919 |
s = reactor.selectable(handler=self, delegate=sock) |
| 920 |
s.reading = True |
| 921 |
s._transport = None |
| 922 |
self._selectable = s |
| 923 |
reactor.update(s) |
| 924 |
|
| 925 |
def set_ssl_domain(self, ssl_domain: SSLDomain) -> None: |
| 926 |
self._ssl_domain = ssl_domain |
| 927 |
|
| 928 |
def close(self) -> None: |
| 929 |
if not self._selectable.is_terminal: |
| 930 |
self._selectable.terminate() |
| 931 |
self._selectable.update() |
| 932 |
|
| 933 |
def on_selectable_readable(self, event: Event) -> None: |
| 934 |
s = event.selectable |
| 935 |
|
| 936 |
sock, name = IO.accept(self._selectable) |
| 937 |
_logger.info("Accepted connection from %s", name) |
| 938 |
|
| 939 |
r = self._reactor |
| 940 |
handler = self._handler or r.handler |
| 941 |
c = r.connection(handler) |
| 942 |
c._acceptor = self |
| 943 |
c.url = Url(host=name[0], port=name[1]) |
| 944 |
t = Transport(Transport.SERVER) |
| 945 |
if self._ssl_domain: |
| 946 |
t.ssl(self._ssl_domain) |
| 947 |
t.bind(c) |
| 948 |
|
| 949 |
s = r.selectable(delegate=sock) |
| 950 |
s._transport = t |
| 951 |
t._selectable = s |
| 952 |
IOHandler.update(t, s, r.now) |
| 953 |
|
| 954 |
|
| 955 |
def delay_iter( |
| 956 |
initial: float = 0.1, |
| 957 |
factor: float = 2.0, |
| 958 |
max_delay: float = 10.0, |
| 959 |
max_tries: Optional[int] = None |
| 960 |
) -> Iterator[float]: |
| 961 |
""" |
| 962 |
iterator yielding the next delay in the sequence of delays. The first |
| 963 |
delay is 0 seconds, the second 0.1 seconds, and each subsequent |
| 964 |
call to :meth:`next` doubles the next delay period until a |
| 965 |
maximum value of 10 seconds is reached. |
| 966 |
""" |
| 967 |
yield 0.0 |
| 968 |
tries = 1 |
| 969 |
delay = initial |
| 970 |
while max_tries is None or tries < max_tries: |
| 971 |
yield delay |
| 972 |
tries += 1 |
| 973 |
delay = min(max_delay, factor * delay) |
| 974 |
|
| 975 |
|
| 976 |
class Backoff(object): |
| 977 |
""" |
| 978 |
A reconnect strategy involving an increasing delay between |
| 979 |
retries, up to a maximum or 10 seconds. Repeated calls |
| 980 |
to :meth:`next` returns a value for the next delay, starting |
| 981 |
with an initial value of 0 seconds. |
| 982 |
""" |
| 983 |
|
| 984 |
def __init__(self, **kwargs) -> None: |
| 985 |
self.kwargs = kwargs |
| 986 |
self.iter = delay_iter(**self.kwargs) |
| 987 |
|
| 988 |
def __iter__(self) -> Iterator[float]: |
| 989 |
return self.iter |
| 990 |
|
| 991 |
|
| 992 |
def make_backoff_wrapper( |
| 993 |
backoff: Optional[Union[List[Union[float, int]], bool, Backoff]] |
| 994 |
) -> Optional[Union[List[Union[float, int]], bool, Backoff]]: |
| 995 |
""" |
| 996 |
Make a wrapper for a backoff object: |
| 997 |
If the object conforms to the old protocol (has reset and next methods) then |
| 998 |
wrap it in an iterable that returns an iterator suitable for the new backoff approach |
| 999 |
otherwise assume it is fine as it is! |
| 1000 |
""" |
| 1001 |
class WrappedBackoff(object): |
| 1002 |
def __init__(self, backoff): |
| 1003 |
self.backoff = backoff |
| 1004 |
|
| 1005 |
def __iter__(self): |
| 1006 |
self.backoff.reset() |
| 1007 |
return self |
| 1008 |
|
| 1009 |
def __next__(self): |
| 1010 |
return self.backoff.next() |
| 1011 |
if hasattr(backoff, 'reset') and hasattr(backoff, 'next'): |
| 1012 |
return WrappedBackoff(backoff) |
| 1013 |
else: |
| 1014 |
return backoff |
| 1015 |
|
| 1016 |
|
| 1017 |
class Urls(object): |
| 1018 |
def __init__(self, values: List[Union[Url, str]]) -> None: |
| 1019 |
self.values = [Url(v) for v in values] |
| 1020 |
|
| 1021 |
def __iter__(self) -> Iterator[Url]: |
| 1022 |
return iter(self.values) |
| 1023 |
|
| 1024 |
|
| 1025 |
class _Connector(Handler): |
| 1026 |
""" |
| 1027 |
Internal handler that triggers the necessary socket connect for an |
| 1028 |
opened connection. |
| 1029 |
""" |
| 1030 |
|
| 1031 |
def __init__(self, connection: Connection) -> None: |
| 1032 |
self.connection = connection |
| 1033 |
self.address = None |
| 1034 |
self.heartbeat = None |
| 1035 |
self.reconnect = None |
| 1036 |
self.ssl_domain = None |
| 1037 |
self.allow_insecure_mechs = True |
| 1038 |
self.allowed_mechs = None |
| 1039 |
self.sasl_enabled = True |
| 1040 |
self.user = None |
| 1041 |
self.password = None |
| 1042 |
self.virtual_host = None |
| 1043 |
self.ssl_sni = None |
| 1044 |
self.max_frame_size = None |
| 1045 |
self._connect_sequence = None |
| 1046 |
self._next_url = None |
| 1047 |
|
| 1048 |
def _connect(self, connection: Connection, url: Url) -> None: |
| 1049 |
connection.url = url |
| 1050 |
# if virtual-host not set, use host from address as default |
| 1051 |
if self.virtual_host is None: |
| 1052 |
connection.hostname = url.host |
| 1053 |
_logger.info("Connecting to %r..." % url) |
| 1054 |
|
| 1055 |
transport = Transport() |
| 1056 |
if self.sasl_enabled: |
| 1057 |
sasl = transport.sasl() |
| 1058 |
sasl.allow_insecure_mechs = self.allow_insecure_mechs |
| 1059 |
if url.username: |
| 1060 |
connection.user = url.username |
| 1061 |
elif self.user: |
| 1062 |
connection.user = self.user |
| 1063 |
if url.password: |
| 1064 |
connection.password = url.password |
| 1065 |
elif self.password: |
| 1066 |
connection.password = self.password |
| 1067 |
if self.allowed_mechs: |
| 1068 |
sasl.allowed_mechs(self.allowed_mechs) |
| 1069 |
transport.bind(connection) |
| 1070 |
if self.heartbeat: |
| 1071 |
transport.idle_timeout = self.heartbeat |
| 1072 |
if url.scheme == 'amqps': |
| 1073 |
if not self.ssl_domain: |
| 1074 |
raise SSLUnavailable("amqps: SSL libraries not found") |
| 1075 |
self.ssl = SSL(transport, self.ssl_domain) |
| 1076 |
self.ssl.peer_hostname = self.ssl_sni or self.virtual_host or url.host |
| 1077 |
if self.max_frame_size: |
| 1078 |
transport.max_frame_size = self.max_frame_size |
| 1079 |
|
| 1080 |
def on_connection_local_open(self, event: Event) -> None: |
| 1081 |
if self.reconnect is None: |
| 1082 |
self._connect_sequence = ((delay, url) for delay in delay_iter() for url in self.address) |
| 1083 |
elif self.reconnect is False: |
| 1084 |
self._connect_sequence = ((delay, url) for delay in delay_iter(max_tries=1) for url in self.address) |
| 1085 |
else: |
| 1086 |
self._connect_sequence = ((delay, url) for delay in self.reconnect for url in self.address) |
| 1087 |
_, url = next(self._connect_sequence) # Ignore delay as we assume first delay must be 0 |
| 1088 |
self._connect(event.connection, url) |
| 1089 |
|
| 1090 |
def on_connection_remote_open(self, event: Event) -> None: |
| 1091 |
_logger.info("Connected to %s" % event.connection.hostname) |
| 1092 |
if self.reconnect is None: |
| 1093 |
self._connect_sequence = ((delay, url) for delay in delay_iter() for url in self.address) |
| 1094 |
elif self.reconnect: |
| 1095 |
self._connect_sequence = ((delay, url) for delay in self.reconnect for url in self.address) |
| 1096 |
else: |
| 1097 |
self._connect_sequence = None # Help take out the garbage |
| 1098 |
|
| 1099 |
def on_transport_closed(self, event: Event) -> None: |
| 1100 |
if self.connection is None: |
| 1101 |
|
| 1102 |
return |
| 1103 |
|
| 1104 |
if not self.connection.state & Endpoint.LOCAL_ACTIVE: |
| 1105 |
_logger.info("Disconnected, already closed") |
| 1106 |
elif self.reconnect is False: |
| 1107 |
_logger.info("Disconnected, reconnect disabled") |
| 1108 |
else: |
| 1109 |
try: |
| 1110 |
event.transport.unbind() |
| 1111 |
delay, url = next(self._connect_sequence) |
| 1112 |
if delay == 0: |
| 1113 |
_logger.info("Disconnected, reconnecting immediately...") |
| 1114 |
self._connect(self.connection, url) |
| 1115 |
return |
| 1116 |
else: |
| 1117 |
_logger.info("Disconnected will try to reconnect after %s seconds" % delay) |
| 1118 |
self._next_url = url |
| 1119 |
event.reactor.schedule(delay, self) |
| 1120 |
return |
| 1121 |
except StopIteration: |
| 1122 |
_logger.info("Disconnected, giving up retrying") |
| 1123 |
|
| 1124 |
# See connector.cpp: conn.free()/pn_connection_release() here? |
| 1125 |
self.connection = None |
| 1126 |
|
| 1127 |
def on_timer_task(self, event: Event) -> None: |
| 1128 |
if self._next_url: |
| 1129 |
self._connect(self.connection, self._next_url) |
| 1130 |
self._next_url = None |
| 1131 |
|
| 1132 |
|
| 1133 |
class SSLConfig(object): |
| 1134 |
def __init__(self) -> None: |
| 1135 |
self.client = SSLDomain(SSLDomain.MODE_CLIENT) |
| 1136 |
self.server = SSLDomain(SSLDomain.MODE_SERVER) |
| 1137 |
|
| 1138 |
def set_credentials(self, cert_file, key_file, password): |
| 1139 |
self.client.set_credentials(cert_file, key_file, password) |
| 1140 |
self.server.set_credentials(cert_file, key_file, password) |
| 1141 |
|
| 1142 |
def set_trusted_ca_db(self, certificate_db): |
| 1143 |
self.client.set_trusted_ca_db(certificate_db) |
| 1144 |
self.server.set_trusted_ca_db(certificate_db) |
| 1145 |
|
| 1146 |
|
| 1147 |
def _find_config_file() -> Optional[str]: |
| 1148 |
confname = 'connect.json' |
| 1149 |
confpath = ['.', os.path.expanduser('~/.config/messaging'), '/etc/messaging'] |
| 1150 |
for d in confpath: |
| 1151 |
f = os.path.join(d, confname) |
| 1152 |
if os.path.isfile(f): |
| 1153 |
return f |
| 1154 |
return None |
| 1155 |
|
| 1156 |
|
| 1157 |
def _get_default_config() -> Dict[str, Any]: |
| 1158 |
conf = os.environ.get('MESSAGING_CONNECT_FILE') or _find_config_file() |
| 1159 |
if conf and os.path.isfile(conf): |
| 1160 |
with open(conf, 'r') as f: |
| 1161 |
json_text = f.read() |
| 1162 |
json_text = _strip_json_comments(json_text) |
| 1163 |
return json.loads(json_text) |
| 1164 |
else: |
| 1165 |
return {} |
| 1166 |
|
| 1167 |
|
| 1168 |
def _strip_json_comments(json_text: str) -> str: |
| 1169 |
"""This strips c-style comments from text, taking into account '/*comments*/' and '//comments' |
| 1170 |
nested inside a string etc.""" |
| 1171 |
def replacer(match): |
| 1172 |
s = match.group(0) |
| 1173 |
if s.startswith('/'): |
| 1174 |
return " " # note: a space and not an empty string |
| 1175 |
else: |
| 1176 |
return s |
| 1177 |
pattern = re.compile(r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"', re.DOTALL | re.MULTILINE) |
| 1178 |
return re.sub(pattern, replacer, json_text) |
| 1179 |
|
| 1180 |
|
| 1181 |
def _get_default_port_for_scheme(scheme: str) -> int: |
| 1182 |
if scheme == 'amqps': |
| 1183 |
return 5671 |
| 1184 |
else: |
| 1185 |
return 5672 |
| 1186 |
|
| 1187 |
|
| 1188 |
class Container(Reactor): |
| 1189 |
""" |
| 1190 |
A representation of the AMQP concept of a 'container', which |
| 1191 |
loosely speaking is something that establishes links to or from |
| 1192 |
another container, over which messages are transfered. This is |
| 1193 |
an extension to the Reactor class that adds convenience methods |
| 1194 |
for creating connections and sender- or receiver- links. |
| 1195 |
""" |
| 1196 |
|
| 1197 |
def __init__(self, *handlers, **kwargs) -> None: |
| 1198 |
super(Container, self).__init__(*handlers, **kwargs) |
| 1199 |
if "impl" not in kwargs: |
| 1200 |
try: |
| 1201 |
self.ssl = SSLConfig() |
| 1202 |
except SSLUnavailable: |
| 1203 |
self.ssl = None |
| 1204 |
self.global_handler = GlobalOverrides(kwargs.get('global_handler', self.global_handler)) |
| 1205 |
self.trigger = None |
| 1206 |
self.container_id = str(_generate_uuid()) |
| 1207 |
self.allow_insecure_mechs = True |
| 1208 |
self.allowed_mechs = None |
| 1209 |
self.sasl_enabled = True |
| 1210 |
self.user = None |
| 1211 |
self.password = None |
| 1212 |
|
| 1213 |
def connect( |
| 1214 |
self, |
| 1215 |
url: Optional[Union[str, Url]] = None, |
| 1216 |
urls: Optional[List[str]] = None, |
| 1217 |
address: Optional[str] = None, |
| 1218 |
handler: Optional[Handler] = None, |
| 1219 |
reconnect: Union[None, Literal[False], Backoff] = None, |
| 1220 |
heartbeat: Optional[float] = None, |
| 1221 |
ssl_domain: Optional[SSLDomain] = None, |
| 1222 |
**kwargs |
| 1223 |
) -> Connection: |
| 1224 |
""" |
| 1225 |
Initiates the establishment of an AMQP connection. |
| 1226 |
|
| 1227 |
An optional JSON configuration file may be used to specify some connection |
| 1228 |
parameters. If present, these will override some of those given in this call |
| 1229 |
(see note below). Some connection parameters (for SSL/TLS) can only be |
| 1230 |
provided through this file. The configuration file is located by searching |
| 1231 |
for it as follows: |
| 1232 |
|
| 1233 |
1. The location set in the environment variable ``MESSAGING_CONNECT_FILE`` |
| 1234 |
2. ``./connect.json`` |
| 1235 |
3. ``~/.config/messaging/connect.json`` |
| 1236 |
4. ``/etc/messaging/connect.json`` |
| 1237 |
|
| 1238 |
To use SSL/TLS for encryption (when an ``amqps`` URL scheme is used), the above |
| 1239 |
configuration file must contain a ``tls`` submap containing the following |
| 1240 |
configuration entries (See :class:`proton.SSLDomain` for details): |
| 1241 |
|
| 1242 |
* ``ca``: Path to a database of trusted CAs that the server will advertise. |
| 1243 |
* ``cert``: Path to a file/database containing the identifying certificate. |
| 1244 |
* ``key``: An optional key to access the identifying certificate. |
| 1245 |
* ``verify``: If ``False``, do not verify the peer name |
| 1246 |
(:const:`proton.SSLDomain.ANONYMOUS_PEER`) or certificate. By default |
| 1247 |
(or if ``True``) verify the peer name and certificate using the |
| 1248 |
``ca`` above (:const:`proton.SSLDomain.VERIFY_PEER_NAME`). |
| 1249 |
|
| 1250 |
:param url: URL string of process to connect to |
| 1251 |
:param urls: list of URL strings of process to try to connect to |
| 1252 |
|
| 1253 |
:param reconnect: Reconnect is enabled by default. You can |
| 1254 |
pass in an instance of :class:`Backoff` to control reconnect behavior. |
| 1255 |
A value of ``False`` will prevent the library from automatically |
| 1256 |
trying to reconnect if the underlying socket is disconnected |
| 1257 |
before the connection has been closed. |
| 1258 |
|
| 1259 |
:param heartbeat: A value in seconds indicating the |
| 1260 |
desired frequency of heartbeats used to test the underlying |
| 1261 |
socket is alive. |
| 1262 |
|
| 1263 |
:param ssl_domain: SSL configuration. |
| 1264 |
|
| 1265 |
:param handler: a connection scoped handler that will be |
| 1266 |
called to process any events in the scope of this connection |
| 1267 |
or its child links. |
| 1268 |
|
| 1269 |
:param kwargs: |
| 1270 |
|
| 1271 |
* ``sasl_enabled`` (``bool``), which determines whether a sasl layer |
| 1272 |
is used for the connection. |
| 1273 |
* ``allowed_mechs`` (``str``), an optional string specifying the |
| 1274 |
SASL mechanisms allowed for this connection; the value is a |
| 1275 |
space-separated list of mechanism names; the mechanisms allowed |
| 1276 |
by default are determined by your SASL library and system |
| 1277 |
configuration, with two exceptions: ``GSSAPI`` and ``GSS-SPNEGO`` |
| 1278 |
are disabled by default; to enable them, you must explicitly add |
| 1279 |
them using this option; clients must set the allowed mechanisms |
| 1280 |
before the outgoing connection is attempted; servers must set |
| 1281 |
them before the listening connection is setup. |
| 1282 |
* ``allow_insecure_mechs`` (``bool``), a flag indicating whether insecure |
| 1283 |
mechanisms, such as PLAIN over a non-encrypted socket, are |
| 1284 |
allowed. |
| 1285 |
* ``password`` (``str``), the authentication secret. Ignored without ``user`` |
| 1286 |
kwarg also being present. |
| 1287 |
* ``user`` (``str``), the user to authenticate. |
| 1288 |
* ``virtual_host`` (``str``), the hostname to set in the Open performative |
| 1289 |
used by peer to determine the correct back-end service for |
| 1290 |
the client; if ``virtual_host`` is not supplied the host field |
| 1291 |
from the URL is used instead. |
| 1292 |
* ``offered_capabilities``, a list of capabilities being offered to the |
| 1293 |
peer. The list must contain symbols (or strings, which will be converted |
| 1294 |
to symbols). |
| 1295 |
* ``desired_capabilities``, a list of capabilities desired from the peer. |
| 1296 |
The list must contain symbols (or strings, which will be converted |
| 1297 |
to symbols). |
| 1298 |
* ``properties``, a list of connection properties. This must be a map |
| 1299 |
with symbol keys (or string keys, which will be converted to symbol keys). |
| 1300 |
* ``sni`` (``str``), a hostname to use with SSL/TLS Server Name Indication (SNI) |
| 1301 |
* ``max_frame_size`` (``int``), the maximum allowable TCP packet size between the |
| 1302 |
peers. |
| 1303 |
|
| 1304 |
:return: A new connection object. |
| 1305 |
|
| 1306 |
.. note:: Only one of ``url`` or ``urls`` should be specified. |
| 1307 |
|
| 1308 |
.. note:: The following kwargs will be overridden by the values found |
| 1309 |
in the JSON configuration file (if they exist there): |
| 1310 |
|
| 1311 |
* ``password`` |
| 1312 |
* ``user`` |
| 1313 |
|
| 1314 |
and the following kwargs will be overridden by the values found in the ``sasl`` |
| 1315 |
sub-map of the above configuration file (if they exist there): |
| 1316 |
|
| 1317 |
* ``sasl_enabled`` |
| 1318 |
* ``allowed_mechs`` |
| 1319 |
""" |
| 1320 |
if not url and not urls and not address: |
| 1321 |
config = _get_default_config() |
| 1322 |
scheme = config.get('scheme', 'amqps') |
| 1323 |
_url = "%s://%s:%s" % (scheme, config.get('host', 'localhost'), |
| 1324 |
config.get('port', _get_default_port_for_scheme(scheme))) |
| 1325 |
_ssl_domain = None |
| 1326 |
_kwargs = kwargs |
| 1327 |
if config.get('user'): |
| 1328 |
_kwargs['user'] = config.get('user') |
| 1329 |
if config.get('password'): |
| 1330 |
_kwargs['password'] = config.get('password') |
| 1331 |
sasl_config = config.get('sasl', {}) |
| 1332 |
_kwargs['sasl_enabled'] = sasl_config.get('enabled', True) |
| 1333 |
if sasl_config.get('mechanisms'): |
| 1334 |
_kwargs['allowed_mechs'] = sasl_config.get('mechanisms') |
| 1335 |
tls_config = config.get('tls', {}) |
| 1336 |
if scheme == 'amqps': |
| 1337 |
_ssl_domain = SSLDomain(SSLDomain.MODE_CLIENT) |
| 1338 |
ca = tls_config.get('ca') |
| 1339 |
cert = tls_config.get('cert') |
| 1340 |
key = tls_config.get('key') |
| 1341 |
verify = tls_config.get('verify', True) |
| 1342 |
if ca: |
| 1343 |
_ssl_domain.set_trusted_ca_db(str(ca)) |
| 1344 |
if not verify: |
| 1345 |
_ssl_domain.set_peer_authentication(SSLDomain.ANONYMOUS_PEER, None) |
| 1346 |
if cert and key: |
| 1347 |
_ssl_domain.set_credentials(str(cert), str(key), None) |
| 1348 |
|
| 1349 |
return self._connect(_url, handler=handler, reconnect=reconnect, |
| 1350 |
heartbeat=heartbeat, ssl_domain=_ssl_domain, **_kwargs) |
| 1351 |
else: |
| 1352 |
return self._connect(url=url, urls=urls, handler=handler, reconnect=reconnect, |
| 1353 |
heartbeat=heartbeat, ssl_domain=ssl_domain, **kwargs) |
| 1354 |
|
| 1355 |
def _connect( |
| 1356 |
self, |
| 1357 |
url: Optional[Union[str, Url]] = None, |
| 1358 |
urls: Optional[List[str]] = None, |
| 1359 |
handler: Optional['Handler'] = None, |
| 1360 |
reconnect: Optional[Union[List[Union[float, int]], bool, Backoff]] = None, |
| 1361 |
heartbeat: None = None, |
| 1362 |
ssl_domain: Optional[SSLDomain] = None, |
| 1363 |
**kwargs |
| 1364 |
) -> Connection: |
| 1365 |
conn = self.connection(handler) |
| 1366 |
conn.container = self.container_id or str(_generate_uuid()) |
| 1367 |
conn.offered_capabilities = kwargs.get('offered_capabilities') |
| 1368 |
conn.desired_capabilities = kwargs.get('desired_capabilities') |
| 1369 |
conn.properties = kwargs.get('properties') |
| 1370 |
|
| 1371 |
connector = _Connector(conn) |
| 1372 |
connector.allow_insecure_mechs = kwargs.get('allow_insecure_mechs', self.allow_insecure_mechs) |
| 1373 |
connector.allowed_mechs = kwargs.get('allowed_mechs', self.allowed_mechs) |
| 1374 |
connector.sasl_enabled = kwargs.get('sasl_enabled', self.sasl_enabled) |
| 1375 |
connector.user = kwargs.get('user', self.user) |
| 1376 |
connector.password = kwargs.get('password', self.password) |
| 1377 |
connector.virtual_host = kwargs.get('virtual_host') |
| 1378 |
if connector.virtual_host: |
| 1379 |
# only set hostname if virtual-host is a non-empty string |
| 1380 |
conn.hostname = connector.virtual_host |
| 1381 |
connector.ssl_sni = kwargs.get('sni') |
| 1382 |
connector.max_frame_size = kwargs.get('max_frame_size') |
| 1383 |
|
| 1384 |
conn._overrides = connector |
| 1385 |
if url: |
| 1386 |
connector.address = Urls([url]) |
| 1387 |
elif urls: |
| 1388 |
connector.address = Urls(urls) |
| 1389 |
else: |
| 1390 |
raise ValueError("One of url or urls required") |
| 1391 |
if heartbeat: |
| 1392 |
connector.heartbeat = heartbeat |
| 1393 |
|
| 1394 |
connector.reconnect = make_backoff_wrapper(reconnect) |
| 1395 |
|
| 1396 |
# use container's default client domain if none specified. This is |
| 1397 |
# only necessary of the URL specifies the "amqps:" scheme |
| 1398 |
connector.ssl_domain = ssl_domain or (self.ssl and self.ssl.client) |
| 1399 |
conn._session_policy = SessionPerConnection() # todo: make configurable |
| 1400 |
conn.open() |
| 1401 |
return conn |
| 1402 |
|
| 1403 |
def _get_id(self, container: str, remote: Optional[str], local: Optional[str]) -> str: |
| 1404 |
if local and remote: |
| 1405 |
return "%s-%s-%s" % (container, remote, local) |
| 1406 |
elif local: |
| 1407 |
return "%s-%s" % (container, local) |
| 1408 |
elif remote: |
| 1409 |
return "%s-%s" % (container, remote) |
| 1410 |
else: |
| 1411 |
return "%s-%s" % (container, str(_generate_uuid())) |
| 1412 |
|
| 1413 |
def _get_session(self, context: Connection) -> Session: |
| 1414 |
if isinstance(context, Url): |
| 1415 |
return self._get_session(self.connect(url=context)) |
| 1416 |
elif isinstance(context, Session): |
| 1417 |
return context |
| 1418 |
elif isinstance(context, Connection): |
| 1419 |
if hasattr(context, '_session_policy'): |
| 1420 |
return context._session_policy.session(context) |
| 1421 |
else: |
| 1422 |
return _create_session(context) |
| 1423 |
else: |
| 1424 |
return context.session() |
| 1425 |
|
| 1426 |
def create_sender( |
| 1427 |
self, |
| 1428 |
context: Union[str, Url, Connection], |
| 1429 |
target: Optional[str] = None, |
| 1430 |
source: Optional[str] = None, |
| 1431 |
name: Optional[str] = None, |
| 1432 |
handler: Optional[Handler] = None, |
| 1433 |
tags: Optional[Callable[[], bytes]] = None, |
| 1434 |
options: Optional[Union['SenderOption', List['SenderOption'], 'LinkOption', List['LinkOption']]] = None |
| 1435 |
) -> 'Sender': |
| 1436 |
""" |
| 1437 |
Initiates the establishment of a link over which messages can |
| 1438 |
be sent. |
| 1439 |
|
| 1440 |
There are two patterns of use: |
| 1441 |
|
| 1442 |
1. A connection can be passed as the first argument, in which |
| 1443 |
case the link is established on that connection. In this case |
| 1444 |
the target address can be specified as the second argument (or |
| 1445 |
as a keyword argument). The source address can also be specified |
| 1446 |
if desired. |
| 1447 |
|
| 1448 |
2. Alternatively a URL can be passed as the first argument. In |
| 1449 |
this case a new connection will be established on which the link |
| 1450 |
will be attached. If a path is specified and the target is not, |
| 1451 |
then the path of the URL is used as the target address. |
| 1452 |
|
| 1453 |
The name of the link may be specified if desired, otherwise a |
| 1454 |
unique name will be generated. |
| 1455 |
|
| 1456 |
Various :class:`LinkOption` s can be specified to further control the |
| 1457 |
attachment. |
| 1458 |
|
| 1459 |
:param context: A connection object or a URL. |
| 1460 |
:param target: Address of target node. |
| 1461 |
:param source: Address of source node. |
| 1462 |
:param name: Sender name. |
| 1463 |
:param handler: Event handler for this sender. |
| 1464 |
:param tags: Function to generate tags for this sender of the form ``def simple_tags():`` and returns a ``bytes`` type |
| 1465 |
:param options: A single option, or a list of sender options |
| 1466 |
|
| 1467 |
:return: New sender instance. |
| 1468 |
""" |
| 1469 |
if isstring(context): |
| 1470 |
context = Url(context) |
| 1471 |
if isinstance(context, Url) and not target: |
| 1472 |
target = context.path |
| 1473 |
session = self._get_session(context) |
| 1474 |
snd = session.sender(name or self._get_id(session.connection.container, target, source)) |
| 1475 |
if source: |
| 1476 |
snd.source.address = source |
| 1477 |
if target: |
| 1478 |
snd.target.address = target |
| 1479 |
if handler is not None: |
| 1480 |
snd.handler = handler |
| 1481 |
if tags: |
| 1482 |
snd.tag_generator = tags |
| 1483 |
_apply_link_options(options, snd) |
| 1484 |
snd.open() |
| 1485 |
return snd |
| 1486 |
|
| 1487 |
def create_receiver( |
| 1488 |
self, |
| 1489 |
context: Union[Connection, Url, str], |
| 1490 |
source: Optional[str] = None, |
| 1491 |
target: Optional[str] = None, |
| 1492 |
name: Optional[str] = None, |
| 1493 |
dynamic: bool = False, |
| 1494 |
handler: Optional[Handler] = None, |
| 1495 |
options: Optional[Union[ReceiverOption, List[ReceiverOption], LinkOption, List[LinkOption]]] = None |
| 1496 |
) -> 'Receiver': |
| 1497 |
""" |
| 1498 |
Initiates the establishment of a link over which messages can |
| 1499 |
be received (aka a subscription). |
| 1500 |
|
| 1501 |
There are two patterns of use: |
| 1502 |
|
| 1503 |
(1) A connection can be passed as the first argument, in which |
| 1504 |
case the link is established on that connection. In this case |
| 1505 |
the source address can be specified as the second argument (or |
| 1506 |
as a keyword argument). The target address can also be specified |
| 1507 |
if desired. |
| 1508 |
|
| 1509 |
(2) Alternatively a URL can be passed as the first argument. In |
| 1510 |
this case a new connection will be established on which the link |
| 1511 |
will be attached. If a path is specified and the source is not, |
| 1512 |
then the path of the URL is used as the target address. |
| 1513 |
|
| 1514 |
The name of the link may be specified if desired, otherwise a |
| 1515 |
unique name will be generated. |
| 1516 |
|
| 1517 |
Various :class:`LinkOption` s can be specified to further control the |
| 1518 |
attachment. |
| 1519 |
|
| 1520 |
:param context: A connection object or a URL. |
| 1521 |
:param source: Address of source node. |
| 1522 |
:param target: Address of target node. |
| 1523 |
:param name: Receiver name. |
| 1524 |
:param dynamic: If ``True``, indicates dynamic creation of the receiver. |
| 1525 |
:param handler: Event handler for this receiver. |
| 1526 |
:param options: A single option, or a list of receiver options |
| 1527 |
|
| 1528 |
:return: New receiver instance. |
| 1529 |
""" |
| 1530 |
if isstring(context): |
| 1531 |
context = Url(context) |
| 1532 |
if isinstance(context, Url) and not source: |
| 1533 |
source = context.path |
| 1534 |
session = self._get_session(context) |
| 1535 |
rcv = session.receiver(name or self._get_id(session.connection.container, source, target)) |
| 1536 |
if source: |
| 1537 |
rcv.source.address = source |
| 1538 |
if dynamic: |
| 1539 |
rcv.source.dynamic = True |
| 1540 |
if target: |
| 1541 |
rcv.target.address = target |
| 1542 |
if handler is not None: |
| 1543 |
rcv.handler = handler |
| 1544 |
_apply_link_options(options, rcv) |
| 1545 |
rcv.open() |
| 1546 |
return rcv |
| 1547 |
|
| 1548 |
def declare_transaction( |
| 1549 |
self, |
| 1550 |
context: Connection, |
| 1551 |
handler: Optional['TransactionHandler'] = None, |
| 1552 |
settle_before_discharge: bool = False |
| 1553 |
) -> Transaction: |
| 1554 |
""" |
| 1555 |
Declare a local transaction. |
| 1556 |
|
| 1557 |
:param context: Context for the transaction, usually the connection. |
| 1558 |
:param handler: Handler for transactional events. |
| 1559 |
:param settle_before_discharge: Settle all transaction control messages before |
| 1560 |
the transaction is discharged. |
| 1561 |
""" |
| 1562 |
if not _get_attr(context, '_txn_ctrl'): |
| 1563 |
class InternalTransactionHandler(OutgoingMessageHandler): |
| 1564 |
def __init__(self): |
| 1565 |
super(InternalTransactionHandler, self).__init__(auto_settle=True) |
| 1566 |
|
| 1567 |
def on_settled(self, event): |
| 1568 |
if hasattr(event.delivery, "transaction"): |
| 1569 |
event.transaction = event.delivery.transaction |
| 1570 |
event.delivery.transaction.handle_outcome(event) |
| 1571 |
|
| 1572 |
def on_unhandled(self, method, event): |
| 1573 |
if handler: |
| 1574 |
event.dispatch(handler) |
| 1575 |
|
| 1576 |
context._txn_ctrl = self.create_sender(context, None, name='txn-ctrl', handler=InternalTransactionHandler()) |
| 1577 |
context._txn_ctrl.target.type = Terminus.COORDINATOR |
| 1578 |
context._txn_ctrl.target.capabilities.put_object(symbol(u'amqp:local-transactions')) |
| 1579 |
return Transaction(context._txn_ctrl, handler, settle_before_discharge) |
| 1580 |
|
| 1581 |
def listen(self, url: Union[str, Url], ssl_domain: Optional[SSLDomain] = None) -> Acceptor: |
| 1582 |
""" |
| 1583 |
Initiates a server socket, accepting incoming AMQP connections |
| 1584 |
on the interface and port specified. |
| 1585 |
|
| 1586 |
:param url: URL on which to listen for incoming AMQP connections. |
| 1587 |
:param ssl_domain: SSL configuration object if SSL is to be used, ``None`` otherwise. |
| 1588 |
""" |
| 1589 |
url = Url(url) |
| 1590 |
acceptor = self.acceptor(url.host, url.port) |
| 1591 |
ssl_config = ssl_domain |
| 1592 |
if not ssl_config and url.scheme == 'amqps': |
| 1593 |
# use container's default server domain |
| 1594 |
if self.ssl: |
| 1595 |
ssl_config = self.ssl.server |
| 1596 |
else: |
| 1597 |
raise SSLUnavailable("amqps: SSL libraries not found") |
| 1598 |
if ssl_config: |
| 1599 |
acceptor.set_ssl_domain(ssl_config) |
| 1600 |
return acceptor |
| 1601 |
|
| 1602 |
def do_work(self, timeout: Optional[float] = None) -> bool: |
| 1603 |
if timeout: |
| 1604 |
self.timeout = timeout |
| 1605 |
return self.process() |