2013-07-23 16:28:15 +01:00
|
|
|
# Copyright 2011 OpenStack Foundation
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
|
|
|
# not use this file except in compliance with the License. You may obtain
|
|
|
|
# a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
|
|
|
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
|
|
|
# License for the specific language governing permissions and limitations
|
|
|
|
# under the License.
|
|
|
|
|
2015-01-21 09:13:10 +01:00
|
|
|
import contextlib
|
2016-04-20 16:08:17 +00:00
|
|
|
import errno
|
2015-05-05 14:37:58 +02:00
|
|
|
import functools
|
2016-02-15 12:27:21 +01:00
|
|
|
import itertools
|
2016-05-06 15:36:18 +03:00
|
|
|
import math
|
2014-11-27 14:46:52 +01:00
|
|
|
import os
|
2015-10-02 13:47:21 -04:00
|
|
|
import random
|
2013-07-23 16:28:15 +01:00
|
|
|
import socket
|
|
|
|
import ssl
|
2016-03-28 06:38:11 -04:00
|
|
|
import sys
|
2015-01-21 09:13:10 +01:00
|
|
|
import threading
|
2013-07-23 16:28:15 +01:00
|
|
|
import time
|
|
|
|
import uuid
|
|
|
|
|
|
|
|
import kombu
|
|
|
|
import kombu.connection
|
|
|
|
import kombu.entity
|
|
|
|
import kombu.messaging
|
2015-01-21 18:46:55 -05:00
|
|
|
from oslo_config import cfg
|
2015-06-22 14:36:11 -04:00
|
|
|
from oslo_log import log as logging
|
2016-09-24 15:22:44 +08:00
|
|
|
from oslo_utils import eventletutils
|
2019-06-04 17:45:59 +02:00
|
|
|
from oslo_utils import importutils
|
2013-12-03 15:41:59 +00:00
|
|
|
import six
|
2018-10-28 17:29:56 +01:00
|
|
|
import six.moves
|
2014-11-17 16:46:46 +01:00
|
|
|
from six.moves.urllib import parse
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2018-09-10 15:11:19 -06:00
|
|
|
import oslo_messaging
|
2015-01-02 14:24:57 -05:00
|
|
|
from oslo_messaging._drivers import amqp as rpc_amqp
|
|
|
|
from oslo_messaging._drivers import amqpdriver
|
2015-04-23 17:08:24 +01:00
|
|
|
from oslo_messaging._drivers import base
|
2015-01-02 14:24:57 -05:00
|
|
|
from oslo_messaging._drivers import common as rpc_common
|
2015-11-29 18:26:32 -05:00
|
|
|
from oslo_messaging._drivers import pool
|
2015-06-16 23:15:20 +02:00
|
|
|
from oslo_messaging import _utils
|
2015-01-02 14:24:57 -05:00
|
|
|
from oslo_messaging import exceptions
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2019-06-04 17:45:59 +02:00
|
|
|
eventlet = importutils.try_import('eventlet')
|
|
|
|
if eventlet and eventletutils.is_monkey_patched("thread"):
|
|
|
|
# Here we initialize module with the native python threading module
|
|
|
|
# if it was already monkey patched by eventlet/greenlet.
|
|
|
|
stdlib_threading = eventlet.patcher.original('threading')
|
|
|
|
else:
|
|
|
|
# Manage the case where we run this driver in a non patched environment
|
|
|
|
# and where user even so configure the driver to run heartbeat through
|
|
|
|
# a python thread, if we don't do that when the heartbeat will start
|
|
|
|
# we will facing an issue by trying to override the threading module.
|
|
|
|
stdlib_threading = threading
|
|
|
|
|
2016-03-17 15:25:38 +01:00
|
|
|
# NOTE(sileht): don't exists in py2 socket module
|
|
|
|
TCP_USER_TIMEOUT = 18
|
|
|
|
|
2013-07-23 18:14:17 +01:00
|
|
|
rabbit_opts = [
|
2017-02-27 13:43:48 +02:00
|
|
|
cfg.BoolOpt('ssl',
|
|
|
|
default=False,
|
|
|
|
deprecated_name='rabbit_use_ssl',
|
|
|
|
help='Connect over SSL.'),
|
|
|
|
cfg.StrOpt('ssl_version',
|
2013-07-23 16:28:15 +01:00
|
|
|
default='',
|
2017-02-27 13:43:48 +02:00
|
|
|
deprecated_name='kombu_ssl_version',
|
2013-07-23 16:28:15 +01:00
|
|
|
help='SSL version to use (valid only if SSL enabled). '
|
2014-11-25 10:59:05 -06:00
|
|
|
'Valid values are TLSv1 and SSLv23. SSLv2, SSLv3, '
|
|
|
|
'TLSv1_1, and TLSv1_2 may be available on some '
|
|
|
|
'distributions.'
|
2013-07-23 16:28:15 +01:00
|
|
|
),
|
2017-02-27 13:43:48 +02:00
|
|
|
cfg.StrOpt('ssl_key_file',
|
2013-07-23 16:28:15 +01:00
|
|
|
default='',
|
2017-02-27 13:43:48 +02:00
|
|
|
deprecated_name='kombu_ssl_keyfile',
|
2014-02-07 22:13:30 +01:00
|
|
|
help='SSL key file (valid only if SSL enabled).'),
|
2017-02-27 13:43:48 +02:00
|
|
|
cfg.StrOpt('ssl_cert_file',
|
2013-07-23 16:28:15 +01:00
|
|
|
default='',
|
2017-02-27 13:43:48 +02:00
|
|
|
deprecated_name='kombu_ssl_certfile',
|
2014-02-07 22:13:30 +01:00
|
|
|
help='SSL cert file (valid only if SSL enabled).'),
|
2017-02-27 13:43:48 +02:00
|
|
|
cfg.StrOpt('ssl_ca_file',
|
2013-07-23 16:28:15 +01:00
|
|
|
default='',
|
2017-02-27 13:43:48 +02:00
|
|
|
deprecated_name='kombu_ssl_ca_certs',
|
2014-04-03 17:27:48 +08:00
|
|
|
help='SSL certification authority file '
|
|
|
|
'(valid only if SSL enabled).'),
|
2019-06-04 17:45:59 +02:00
|
|
|
cfg.BoolOpt('heartbeat_in_pthread',
|
|
|
|
default=False,
|
2019-09-18 10:29:58 -04:00
|
|
|
help="EXPERIMENTAL: Run the health check heartbeat thread "
|
|
|
|
"through a native python thread. By default if this "
|
|
|
|
"option isn't provided the health check heartbeat will "
|
|
|
|
"inherit the execution model from the parent process. By "
|
|
|
|
"example if the parent process have monkey patched the "
|
|
|
|
"stdlib by using eventlet/greenlet then the heartbeat "
|
2019-06-04 17:45:59 +02:00
|
|
|
"will be run through a green thread."),
|
2014-02-26 15:21:01 -08:00
|
|
|
cfg.FloatOpt('kombu_reconnect_delay',
|
|
|
|
default=1.0,
|
2015-01-28 08:57:21 +01:00
|
|
|
deprecated_group='DEFAULT',
|
2014-02-26 15:21:01 -08:00
|
|
|
help='How long to wait before reconnecting in response to an '
|
|
|
|
'AMQP consumer cancel notification.'),
|
2015-11-27 16:19:37 +02:00
|
|
|
cfg.StrOpt('kombu_compression',
|
|
|
|
help="EXPERIMENTAL: Possible values are: gzip, bz2. If not "
|
2016-08-09 09:57:49 +08:00
|
|
|
"set compression will not be used. This option may not "
|
2015-11-27 16:19:37 +02:00
|
|
|
"be available in future versions."),
|
2015-12-02 09:36:02 +01:00
|
|
|
cfg.IntOpt('kombu_missing_consumer_retry_timeout',
|
|
|
|
deprecated_name="kombu_reconnect_timeout",
|
2015-12-09 19:37:40 +01:00
|
|
|
default=60,
|
2016-07-29 10:59:34 +08:00
|
|
|
help='How long to wait a missing client before abandoning to '
|
2015-12-02 09:36:02 +01:00
|
|
|
'send it its replies. This value should not be longer '
|
|
|
|
'than rpc_response_timeout.'),
|
2015-11-23 17:27:24 +03:00
|
|
|
cfg.StrOpt('kombu_failover_strategy',
|
|
|
|
choices=('round-robin', 'shuffle'),
|
|
|
|
default='round-robin',
|
|
|
|
help='Determines how the next RabbitMQ node is chosen in case '
|
|
|
|
'the one we are currently connected to becomes '
|
|
|
|
'unavailable. Takes effect only if more than one '
|
|
|
|
'RabbitMQ node is provided in config.'),
|
2014-01-16 19:06:31 +01:00
|
|
|
cfg.StrOpt('rabbit_login_method',
|
2016-09-19 16:52:26 -07:00
|
|
|
choices=('PLAIN', 'AMQPLAIN', 'RABBIT-CR-DEMO'),
|
2014-01-16 19:06:31 +01:00
|
|
|
default='AMQPLAIN',
|
2015-01-28 08:57:21 +01:00
|
|
|
deprecated_group='DEFAULT',
|
2014-08-28 06:59:33 +02:00
|
|
|
help='The RabbitMQ login method.'),
|
2013-07-23 16:28:15 +01:00
|
|
|
cfg.IntOpt('rabbit_retry_interval',
|
|
|
|
default=1,
|
2014-02-07 22:13:30 +01:00
|
|
|
help='How frequently to retry connecting with RabbitMQ.'),
|
2013-07-23 16:28:15 +01:00
|
|
|
cfg.IntOpt('rabbit_retry_backoff',
|
|
|
|
default=2,
|
2015-01-28 08:57:21 +01:00
|
|
|
deprecated_group='DEFAULT',
|
2014-01-18 14:36:11 +01:00
|
|
|
help='How long to backoff for between retries when connecting '
|
2014-02-07 22:13:30 +01:00
|
|
|
'to RabbitMQ.'),
|
2015-12-24 15:52:59 +08:00
|
|
|
cfg.IntOpt('rabbit_interval_max',
|
|
|
|
default=30,
|
|
|
|
help='Maximum interval of RabbitMQ connection retries. '
|
|
|
|
'Default is 30 seconds.'),
|
2013-07-23 16:28:15 +01:00
|
|
|
cfg.BoolOpt('rabbit_ha_queues',
|
|
|
|
default=False,
|
2015-01-28 08:57:21 +01:00
|
|
|
deprecated_group='DEFAULT',
|
2016-02-19 11:14:03 +08:00
|
|
|
help='Try to use HA queues in RabbitMQ (x-ha-policy: all). '
|
|
|
|
'If you change this option, you must wipe the RabbitMQ '
|
|
|
|
'database. In RabbitMQ 3.0, queue mirroring is no longer '
|
|
|
|
'controlled by the x-ha-policy argument when declaring a '
|
|
|
|
'queue. If you just want to make sure that all queues (except '
|
2016-10-05 15:58:20 +05:30
|
|
|
'those with auto-generated names) are mirrored across all '
|
2016-02-19 11:14:03 +08:00
|
|
|
'nodes, run: '
|
|
|
|
"""\"rabbitmqctl set_policy HA '^(?!amq\.).*' """
|
|
|
|
"""'{"ha-mode": "all"}' \""""),
|
2015-11-20 17:25:58 -05:00
|
|
|
cfg.IntOpt('rabbit_transient_queues_ttl',
|
|
|
|
min=1,
|
2016-03-13 20:41:01 -04:00
|
|
|
default=1800,
|
2015-11-20 17:25:58 -05:00
|
|
|
help='Positive integer representing duration in seconds for '
|
|
|
|
'queue TTL (x-expires). Queues which are unused for the '
|
|
|
|
'duration of the TTL are automatically deleted. The '
|
|
|
|
'parameter affects only reply and fanout queues.'),
|
2016-01-19 22:59:38 -05:00
|
|
|
cfg.IntOpt('rabbit_qos_prefetch_count',
|
|
|
|
default=0,
|
|
|
|
help='Specifies the number of messages to prefetch. Setting to '
|
|
|
|
'zero allows unlimited messages.'),
|
2015-01-21 09:13:10 +01:00
|
|
|
cfg.IntOpt('heartbeat_timeout_threshold',
|
2015-07-07 08:51:12 +02:00
|
|
|
default=60,
|
2015-01-21 09:13:10 +01:00
|
|
|
help="Number of seconds after which the Rabbit broker is "
|
|
|
|
"considered down if heartbeat's keep-alive fails "
|
2019-03-26 10:50:33 +00:00
|
|
|
"(0 disables heartbeat)."),
|
2015-01-21 09:13:10 +01:00
|
|
|
cfg.IntOpt('heartbeat_rate',
|
|
|
|
default=2,
|
|
|
|
help='How often times during the heartbeat_timeout_threshold '
|
|
|
|
'we check the heartbeat.'),
|
2019-07-22 17:27:21 +02:00
|
|
|
cfg.IntOpt('direct_mandatory_flag',
|
|
|
|
default=True,
|
|
|
|
help='Enable/Disable the RabbitMQ mandatory flag '
|
2019-10-03 14:10:28 +02:00
|
|
|
'for direct send. The direct send is used as reply, '
|
|
|
|
'so the MessageUndeliverable exception is raised '
|
|
|
|
'in case the client queue does not exist.'),
|
2013-07-23 16:28:15 +01:00
|
|
|
]
|
|
|
|
|
2013-07-23 17:34:18 +01:00
|
|
|
LOG = logging.getLogger(__name__)
|
2013-07-23 16:28:15 +01:00
|
|
|
|
|
|
|
|
2015-11-20 17:25:58 -05:00
|
|
|
def _get_queue_arguments(rabbit_ha_queues, rabbit_queue_ttl):
|
2013-07-23 16:28:15 +01:00
|
|
|
"""Construct the arguments for declaring a queue.
|
|
|
|
|
2016-02-19 11:14:03 +08:00
|
|
|
If the rabbit_ha_queues option is set, we try to declare a mirrored queue
|
2013-07-23 16:28:15 +01:00
|
|
|
as described here:
|
|
|
|
|
|
|
|
http://www.rabbitmq.com/ha.html
|
|
|
|
|
|
|
|
Setting x-ha-policy to all means that the queue will be mirrored
|
2016-02-19 11:14:03 +08:00
|
|
|
to all nodes in the cluster. In RabbitMQ 3.0, queue mirroring is
|
|
|
|
no longer controlled by the x-ha-policy argument when declaring a
|
|
|
|
queue. If you just want to make sure that all queues (except those
|
|
|
|
with auto-generated names) are mirrored across all nodes, run:
|
|
|
|
rabbitmqctl set_policy HA '^(?!amq\.).*' '{"ha-mode": "all"}'
|
2015-11-20 17:25:58 -05:00
|
|
|
|
|
|
|
If the rabbit_queue_ttl option is > 0, then the queue is
|
|
|
|
declared with the "Queue TTL" value as described here:
|
|
|
|
|
|
|
|
https://www.rabbitmq.com/ttl.html
|
|
|
|
|
|
|
|
Setting a queue TTL causes the queue to be automatically deleted
|
|
|
|
if it is unused for the TTL duration. This is a helpful safeguard
|
|
|
|
to prevent queues with zero consumers from growing without bound.
|
2013-07-23 16:28:15 +01:00
|
|
|
"""
|
2015-11-20 17:25:58 -05:00
|
|
|
args = {}
|
|
|
|
|
|
|
|
if rabbit_ha_queues:
|
|
|
|
args['x-ha-policy'] = 'all'
|
|
|
|
|
|
|
|
if rabbit_queue_ttl > 0:
|
|
|
|
args['x-expires'] = rabbit_queue_ttl * 1000
|
|
|
|
|
|
|
|
return args
|
2013-07-23 16:28:15 +01:00
|
|
|
|
|
|
|
|
2013-11-29 16:03:37 +01:00
|
|
|
class RabbitMessage(dict):
|
|
|
|
def __init__(self, raw_message):
|
|
|
|
super(RabbitMessage, self).__init__(
|
|
|
|
rpc_common.deserialize_msg(raw_message.payload))
|
2015-06-22 14:36:11 -04:00
|
|
|
LOG.trace('RabbitMessage.Init: message %s', self)
|
2013-11-29 16:03:37 +01:00
|
|
|
self._raw_message = raw_message
|
|
|
|
|
|
|
|
def acknowledge(self):
|
2015-06-22 14:36:11 -04:00
|
|
|
LOG.trace('RabbitMessage.acknowledge: message %s', self)
|
2013-11-29 16:03:37 +01:00
|
|
|
self._raw_message.ack()
|
|
|
|
|
2013-12-11 16:50:09 +01:00
|
|
|
def requeue(self):
|
2015-06-22 14:36:11 -04:00
|
|
|
LOG.trace('RabbitMessage.requeue: message %s', self)
|
2013-12-11 16:50:09 +01:00
|
|
|
self._raw_message.requeue()
|
|
|
|
|
2013-11-29 16:03:37 +01:00
|
|
|
|
2015-04-30 17:46:42 +02:00
|
|
|
class Consumer(object):
|
|
|
|
"""Consumer class."""
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2015-05-13 17:51:12 +03:00
|
|
|
def __init__(self, exchange_name, queue_name, routing_key, type, durable,
|
2015-11-20 17:25:58 -05:00
|
|
|
exchange_auto_delete, queue_auto_delete, callback,
|
2016-05-12 21:00:29 +03:00
|
|
|
nowait=False, rabbit_ha_queues=None, rabbit_queue_ttl=0):
|
2016-09-14 18:12:22 +02:00
|
|
|
"""Init the Consumer class with the exchange_name, routing_key,
|
2015-04-30 17:46:42 +02:00
|
|
|
type, durable auto_delete
|
2013-07-23 16:28:15 +01:00
|
|
|
"""
|
2015-04-30 17:46:42 +02:00
|
|
|
self.queue_name = queue_name
|
|
|
|
self.exchange_name = exchange_name
|
|
|
|
self.routing_key = routing_key
|
2015-11-20 17:25:58 -05:00
|
|
|
self.exchange_auto_delete = exchange_auto_delete
|
|
|
|
self.queue_auto_delete = queue_auto_delete
|
2015-04-30 17:46:42 +02:00
|
|
|
self.durable = durable
|
2013-07-23 16:28:15 +01:00
|
|
|
self.callback = callback
|
2015-04-30 17:46:42 +02:00
|
|
|
self.type = type
|
|
|
|
self.nowait = nowait
|
2015-11-20 17:25:58 -05:00
|
|
|
self.queue_arguments = _get_queue_arguments(rabbit_ha_queues,
|
|
|
|
rabbit_queue_ttl)
|
2013-07-23 16:28:15 +01:00
|
|
|
self.queue = None
|
2016-08-04 15:18:25 +03:00
|
|
|
self._declared_on = None
|
2015-04-30 17:46:42 +02:00
|
|
|
self.exchange = kombu.entity.Exchange(
|
|
|
|
name=exchange_name,
|
|
|
|
type=type,
|
|
|
|
durable=self.durable,
|
2015-11-20 17:25:58 -05:00
|
|
|
auto_delete=self.exchange_auto_delete)
|
2015-04-30 17:46:42 +02:00
|
|
|
|
2015-05-01 00:24:46 +02:00
|
|
|
def declare(self, conn):
|
2015-04-30 17:46:42 +02:00
|
|
|
"""Re-declare the queue after a rabbit (re)connect."""
|
2016-08-04 15:18:25 +03:00
|
|
|
|
2015-04-30 17:46:42 +02:00
|
|
|
self.queue = kombu.entity.Queue(
|
|
|
|
name=self.queue_name,
|
2015-05-01 00:24:46 +02:00
|
|
|
channel=conn.channel,
|
2015-04-30 17:46:42 +02:00
|
|
|
exchange=self.exchange,
|
|
|
|
durable=self.durable,
|
2015-11-20 17:25:58 -05:00
|
|
|
auto_delete=self.queue_auto_delete,
|
2015-04-30 17:46:42 +02:00
|
|
|
routing_key=self.routing_key,
|
|
|
|
queue_arguments=self.queue_arguments)
|
2013-07-23 16:28:15 +01:00
|
|
|
|
Fix reconnect race condition with RabbitMQ cluster
Retry Queue creation to workaround race condition
that may happen when both the client and broker race over
exchange creation and deletion respectively which happen only
when the Queue/Exchange were created with auto-delete flag.
Queues/Exchange declared with auto-delete instruct the Broker to
delete the Queue when the last Consumer disconnect from it, and
the Exchange when the last Queue is deleted from this Exchange.
Now in a RabbitMQ cluster setup, if the cluster node that we are
connected to go down, 2 things will happen:
1. From RabbitMQ side, the Queues w/ auto-delete will be deleted
from the other cluster nodes and then the Exchanges that the
Queues are bind to if they were also created w/ auto-delete.
2. From client side, client will reconnect to another cluster
node and call queue.declare() which create Exchanges then
Queues then Binding in that order.
Now in a happy path the queues/exchanges will be deleted from the
broker before client start re-creating them again, but it also
possible that the client first start by creating queues/exchange
as part of the queue.declare() call, which are no-op operations
b/c they alreay existed, but before it could bind Queue to
Exchange, RabbitMQ nodes just received the 'signal' that the
queue doesn't have any consumer so it should be delete, and the
same with exchanges, which will lead to binding fail with
NotFound error.
Illustration of the time line from Client and RabbitMQ cluster
respectively when the race condition happen:
e-declare(E) q-declare(Q) q-bind(Q, E)
-----+------------------+----------------+----------->
e-delete(E)
------------------------------+---------------------->
Change-Id: Ideb73af6f246a8282780cdb204d675d5d4555bf0
Closes-Bug: #1318721
2014-06-27 16:46:47 +02:00
|
|
|
try:
|
2016-05-24 20:45:52 +03:00
|
|
|
LOG.debug('[%s] Queue.declare: %s',
|
|
|
|
conn.connection_id, self.queue_name)
|
Fix reconnect race condition with RabbitMQ cluster
Retry Queue creation to workaround race condition
that may happen when both the client and broker race over
exchange creation and deletion respectively which happen only
when the Queue/Exchange were created with auto-delete flag.
Queues/Exchange declared with auto-delete instruct the Broker to
delete the Queue when the last Consumer disconnect from it, and
the Exchange when the last Queue is deleted from this Exchange.
Now in a RabbitMQ cluster setup, if the cluster node that we are
connected to go down, 2 things will happen:
1. From RabbitMQ side, the Queues w/ auto-delete will be deleted
from the other cluster nodes and then the Exchanges that the
Queues are bind to if they were also created w/ auto-delete.
2. From client side, client will reconnect to another cluster
node and call queue.declare() which create Exchanges then
Queues then Binding in that order.
Now in a happy path the queues/exchanges will be deleted from the
broker before client start re-creating them again, but it also
possible that the client first start by creating queues/exchange
as part of the queue.declare() call, which are no-op operations
b/c they alreay existed, but before it could bind Queue to
Exchange, RabbitMQ nodes just received the 'signal' that the
queue doesn't have any consumer so it should be delete, and the
same with exchanges, which will lead to binding fail with
NotFound error.
Illustration of the time line from Client and RabbitMQ cluster
respectively when the race condition happen:
e-declare(E) q-declare(Q) q-bind(Q, E)
-----+------------------+----------------+----------->
e-delete(E)
------------------------------+---------------------->
Change-Id: Ideb73af6f246a8282780cdb204d675d5d4555bf0
Closes-Bug: #1318721
2014-06-27 16:46:47 +02:00
|
|
|
self.queue.declare()
|
2015-05-01 00:24:46 +02:00
|
|
|
except conn.connection.channel_errors as exc:
|
|
|
|
# NOTE(jrosenboom): This exception may be triggered by a race
|
|
|
|
# condition. Simply retrying will solve the error most of the time
|
|
|
|
# and should work well enough as a workaround until the race
|
|
|
|
# condition itself can be fixed.
|
Fix reconnect race condition with RabbitMQ cluster
Retry Queue creation to workaround race condition
that may happen when both the client and broker race over
exchange creation and deletion respectively which happen only
when the Queue/Exchange were created with auto-delete flag.
Queues/Exchange declared with auto-delete instruct the Broker to
delete the Queue when the last Consumer disconnect from it, and
the Exchange when the last Queue is deleted from this Exchange.
Now in a RabbitMQ cluster setup, if the cluster node that we are
connected to go down, 2 things will happen:
1. From RabbitMQ side, the Queues w/ auto-delete will be deleted
from the other cluster nodes and then the Exchanges that the
Queues are bind to if they were also created w/ auto-delete.
2. From client side, client will reconnect to another cluster
node and call queue.declare() which create Exchanges then
Queues then Binding in that order.
Now in a happy path the queues/exchanges will be deleted from the
broker before client start re-creating them again, but it also
possible that the client first start by creating queues/exchange
as part of the queue.declare() call, which are no-op operations
b/c they alreay existed, but before it could bind Queue to
Exchange, RabbitMQ nodes just received the 'signal' that the
queue doesn't have any consumer so it should be delete, and the
same with exchanges, which will lead to binding fail with
NotFound error.
Illustration of the time line from Client and RabbitMQ cluster
respectively when the race condition happen:
e-declare(E) q-declare(Q) q-bind(Q, E)
-----+------------------+----------------+----------->
e-delete(E)
------------------------------+---------------------->
Change-Id: Ideb73af6f246a8282780cdb204d675d5d4555bf0
Closes-Bug: #1318721
2014-06-27 16:46:47 +02:00
|
|
|
# See https://bugs.launchpad.net/neutron/+bug/1318721 for details.
|
2015-05-01 00:24:46 +02:00
|
|
|
if exc.code == 404:
|
|
|
|
self.queue.declare()
|
|
|
|
else:
|
|
|
|
raise
|
2019-04-04 14:56:25 +02:00
|
|
|
except kombu.exceptions.ConnectionError as exc:
|
|
|
|
# NOTE(gsantomaggio): This exception happens when the
|
|
|
|
# connection is established,but it fails to create the queue.
|
|
|
|
# Add some delay to avoid too many requests to the server.
|
|
|
|
# See: https://bugs.launchpad.net/oslo.messaging/+bug/1822778
|
|
|
|
# for details.
|
|
|
|
if exc.code == 541:
|
|
|
|
interval = 2
|
|
|
|
info = {'sleep_time': interval,
|
|
|
|
'queue': self.queue_name,
|
|
|
|
'err_str': exc
|
|
|
|
}
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.error('Internal amqp error (541) '
|
|
|
|
'during queue declare,'
|
|
|
|
'retrying in %(sleep_time)s seconds. '
|
|
|
|
'Queue: [%(queue)s], '
|
|
|
|
'error message: [%(err_str)s]', info)
|
2019-04-04 14:56:25 +02:00
|
|
|
time.sleep(interval)
|
|
|
|
self.queue.declare()
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
|
2016-08-04 15:18:25 +03:00
|
|
|
self._declared_on = conn.channel
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2016-08-04 15:18:25 +03:00
|
|
|
def consume(self, conn, tag):
|
2013-07-23 16:28:15 +01:00
|
|
|
"""Actually declare the consumer on the amqp channel. This will
|
|
|
|
start the flow of messages from the queue. Using the
|
2015-04-30 08:56:20 +02:00
|
|
|
Connection.consume() will process the messages,
|
2013-07-23 16:28:15 +01:00
|
|
|
calling the appropriate callback.
|
|
|
|
"""
|
|
|
|
|
2016-08-04 15:18:25 +03:00
|
|
|
# Ensure we are on the correct channel before consuming
|
|
|
|
if conn.channel != self._declared_on:
|
|
|
|
self.declare(conn)
|
|
|
|
try:
|
|
|
|
self.queue.consume(callback=self._callback,
|
|
|
|
consumer_tag=six.text_type(tag),
|
|
|
|
nowait=self.nowait)
|
|
|
|
except conn.connection.channel_errors as exc:
|
|
|
|
# We retries once because of some races that we can
|
|
|
|
# recover before informing the deployer
|
|
|
|
# bugs.launchpad.net/oslo.messaging/+bug/1581148
|
|
|
|
# bugs.launchpad.net/oslo.messaging/+bug/1609766
|
|
|
|
# bugs.launchpad.net/neutron/+bug/1318721
|
|
|
|
|
2016-12-09 18:31:06 +00:00
|
|
|
# 406 error code relates to messages that are doubled ack'd
|
|
|
|
|
2016-08-04 15:18:25 +03:00
|
|
|
# At any channel error, the RabbitMQ closes
|
|
|
|
# the channel, but the amqp-lib quietly re-open
|
|
|
|
# it. So, we must reset all tags and declare
|
|
|
|
# all consumers again.
|
|
|
|
conn._new_tags = set(conn._consumers.values())
|
2016-12-09 18:31:06 +00:00
|
|
|
if exc.code == 404 or (exc.code == 406 and
|
|
|
|
exc.method_name == 'Basic.ack'):
|
2016-08-04 15:18:25 +03:00
|
|
|
self.declare(conn)
|
|
|
|
self.queue.consume(callback=self._callback,
|
|
|
|
consumer_tag=six.text_type(tag),
|
|
|
|
nowait=self.nowait)
|
|
|
|
else:
|
|
|
|
raise
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2015-05-12 14:25:47 +03:00
|
|
|
def cancel(self, tag):
|
2015-06-22 14:36:11 -04:00
|
|
|
LOG.trace('ConsumerBase.cancel: canceling %s', tag)
|
2015-05-12 14:25:47 +03:00
|
|
|
self.queue.cancel(six.text_type(tag))
|
|
|
|
|
2015-04-30 17:46:42 +02:00
|
|
|
def _callback(self, message):
|
|
|
|
"""Call callback with deserialized message.
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2015-04-30 17:46:42 +02:00
|
|
|
Messages that are processed and ack'ed.
|
2013-07-23 16:28:15 +01:00
|
|
|
"""
|
|
|
|
|
2015-04-30 17:46:42 +02:00
|
|
|
m2p = getattr(self.queue.channel, 'message_to_python', None)
|
|
|
|
if m2p:
|
|
|
|
message = m2p(message)
|
|
|
|
try:
|
|
|
|
self.callback(RabbitMessage(message))
|
|
|
|
except Exception:
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.exception("Failed to process message ... skipping it.")
|
2016-12-21 16:02:37 +00:00
|
|
|
message.reject()
|
2013-07-23 16:28:15 +01:00
|
|
|
|
|
|
|
|
2015-09-16 14:07:52 +02:00
|
|
|
class DummyConnectionLock(_utils.DummyLock):
|
2015-01-21 09:13:10 +01:00
|
|
|
def heartbeat_acquire(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class ConnectionLock(DummyConnectionLock):
|
2016-09-28 09:09:04 +07:00
|
|
|
"""Lock object to protect access to the kombu connection
|
2015-01-21 09:13:10 +01:00
|
|
|
|
2016-09-28 09:09:04 +07:00
|
|
|
This is a lock object to protect access to the kombu connection
|
2015-01-21 09:13:10 +01:00
|
|
|
object between the heartbeat thread and the driver thread.
|
|
|
|
|
|
|
|
They are two way to acquire this lock:
|
|
|
|
* lock.acquire()
|
|
|
|
* lock.heartbeat_acquire()
|
|
|
|
|
|
|
|
In both case lock.release(), release the lock.
|
|
|
|
|
|
|
|
The goal is that the heartbeat thread always have the priority
|
|
|
|
for acquiring the lock. This ensures we have no heartbeat
|
|
|
|
starvation when the driver sends a lot of messages.
|
|
|
|
|
|
|
|
So when lock.heartbeat_acquire() is called next time the lock
|
2016-03-29 10:59:12 +07:00
|
|
|
is released(), the caller unconditionally acquires
|
2015-01-21 09:13:10 +01:00
|
|
|
the lock, even someone else have asked for the lock before it.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self._workers_waiting = 0
|
|
|
|
self._heartbeat_waiting = False
|
|
|
|
self._lock_acquired = None
|
|
|
|
self._monitor = threading.Lock()
|
|
|
|
self._workers_locks = threading.Condition(self._monitor)
|
|
|
|
self._heartbeat_lock = threading.Condition(self._monitor)
|
2016-09-24 15:22:44 +08:00
|
|
|
self._get_thread_id = eventletutils.fetch_current_thread_functor()
|
2015-01-21 09:13:10 +01:00
|
|
|
|
|
|
|
def acquire(self):
|
|
|
|
with self._monitor:
|
|
|
|
while self._lock_acquired:
|
|
|
|
self._workers_waiting += 1
|
|
|
|
self._workers_locks.wait()
|
|
|
|
self._workers_waiting -= 1
|
|
|
|
self._lock_acquired = self._get_thread_id()
|
|
|
|
|
|
|
|
def heartbeat_acquire(self):
|
|
|
|
# NOTE(sileht): must be called only one time
|
|
|
|
with self._monitor:
|
|
|
|
while self._lock_acquired is not None:
|
|
|
|
self._heartbeat_waiting = True
|
|
|
|
self._heartbeat_lock.wait()
|
|
|
|
self._heartbeat_waiting = False
|
|
|
|
self._lock_acquired = self._get_thread_id()
|
|
|
|
|
|
|
|
def release(self):
|
|
|
|
with self._monitor:
|
|
|
|
if self._lock_acquired is None:
|
|
|
|
raise RuntimeError("We can't release a not acquired lock")
|
|
|
|
thread_id = self._get_thread_id()
|
|
|
|
if self._lock_acquired != thread_id:
|
|
|
|
raise RuntimeError("We can't release lock acquired by another "
|
|
|
|
"thread/greenthread; %s vs %s" %
|
|
|
|
(self._lock_acquired, thread_id))
|
|
|
|
self._lock_acquired = None
|
|
|
|
if self._heartbeat_waiting:
|
|
|
|
self._heartbeat_lock.notify()
|
|
|
|
elif self._workers_waiting > 0:
|
|
|
|
self._workers_locks.notify()
|
|
|
|
|
|
|
|
@contextlib.contextmanager
|
|
|
|
def for_heartbeat(self):
|
|
|
|
self.heartbeat_acquire()
|
|
|
|
try:
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
self.release()
|
|
|
|
|
|
|
|
|
2013-07-23 16:28:15 +01:00
|
|
|
class Connection(object):
|
|
|
|
"""Connection object."""
|
|
|
|
|
2014-03-07 10:46:17 +01:00
|
|
|
pools = {}
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2015-01-21 09:13:10 +01:00
|
|
|
def __init__(self, conf, url, purpose):
|
2015-05-13 17:51:12 +03:00
|
|
|
# NOTE(viktors): Parse config options
|
|
|
|
driver_conf = conf.oslo_messaging_rabbit
|
|
|
|
|
|
|
|
self.interval_start = driver_conf.rabbit_retry_interval
|
|
|
|
self.interval_stepping = driver_conf.rabbit_retry_backoff
|
2015-12-24 15:52:59 +08:00
|
|
|
self.interval_max = driver_conf.rabbit_interval_max
|
2015-05-13 17:51:12 +03:00
|
|
|
|
|
|
|
self.login_method = driver_conf.rabbit_login_method
|
|
|
|
self.rabbit_ha_queues = driver_conf.rabbit_ha_queues
|
2015-11-20 17:25:58 -05:00
|
|
|
self.rabbit_transient_queues_ttl = \
|
|
|
|
driver_conf.rabbit_transient_queues_ttl
|
2016-01-19 22:59:38 -05:00
|
|
|
self.rabbit_qos_prefetch_count = driver_conf.rabbit_qos_prefetch_count
|
2015-05-13 17:51:12 +03:00
|
|
|
self.heartbeat_timeout_threshold = \
|
|
|
|
driver_conf.heartbeat_timeout_threshold
|
|
|
|
self.heartbeat_rate = driver_conf.heartbeat_rate
|
|
|
|
self.kombu_reconnect_delay = driver_conf.kombu_reconnect_delay
|
|
|
|
self.amqp_durable_queues = driver_conf.amqp_durable_queues
|
|
|
|
self.amqp_auto_delete = driver_conf.amqp_auto_delete
|
2017-02-27 13:43:48 +02:00
|
|
|
self.ssl = driver_conf.ssl
|
2015-12-02 09:36:02 +01:00
|
|
|
self.kombu_missing_consumer_retry_timeout = \
|
|
|
|
driver_conf.kombu_missing_consumer_retry_timeout
|
2015-11-23 17:27:24 +03:00
|
|
|
self.kombu_failover_strategy = driver_conf.kombu_failover_strategy
|
2015-11-27 16:19:37 +02:00
|
|
|
self.kombu_compression = driver_conf.kombu_compression
|
2019-06-04 17:45:59 +02:00
|
|
|
self.heartbeat_in_pthread = driver_conf.heartbeat_in_pthread
|
|
|
|
|
|
|
|
if self.heartbeat_in_pthread:
|
|
|
|
# NOTE(hberaud): Experimental: threading module is in use to run
|
|
|
|
# the rabbitmq health check heartbeat. in some situation like
|
|
|
|
# with nova-api, nova need green threads to run the cells
|
|
|
|
# mechanismes in an async mode, so they used eventlet and
|
|
|
|
# greenlet to monkey patch the python stdlib and get green threads.
|
|
|
|
# The issue here is that nova-api run under the apache MPM prefork
|
|
|
|
# module and mod_wsgi. The apache prefork module doesn't support
|
|
|
|
# epoll and recent kernel features, and evenlet is built over epoll
|
|
|
|
# and libevent, so when we run the rabbitmq heartbeat we inherit
|
|
|
|
# from the execution model of the parent process (nova-api), and
|
|
|
|
# in this case we will run the heartbeat through a green thread.
|
|
|
|
# We want to allow users to choose between pthread and
|
|
|
|
# green threads if needed in some specific situations.
|
|
|
|
# This experimental feature allow user to use pthread in an env
|
|
|
|
# that doesn't support eventlet without forcing the parent process
|
|
|
|
# to stop to use eventlet if they need monkey patching for some
|
|
|
|
# specific reasons.
|
|
|
|
# If users want to use pthread we need to make sure that we
|
|
|
|
# will use the *native* threading module for
|
|
|
|
# initialize the heartbeat thread.
|
|
|
|
# Here we override globaly the previously imported
|
|
|
|
# threading module with the native python threading module
|
|
|
|
# if it was already monkey patched by eventlet/greenlet.
|
|
|
|
global threading
|
|
|
|
threading = stdlib_threading
|
2019-07-22 17:27:21 +02:00
|
|
|
self.direct_mandatory_flag = driver_conf.direct_mandatory_flag
|
2015-05-13 17:51:12 +03:00
|
|
|
|
2017-02-27 13:43:48 +02:00
|
|
|
if self.ssl:
|
|
|
|
self.ssl_version = driver_conf.ssl_version
|
|
|
|
self.ssl_key_file = driver_conf.ssl_key_file
|
|
|
|
self.ssl_cert_file = driver_conf.ssl_cert_file
|
|
|
|
self.ssl_ca_file = driver_conf.ssl_ca_file
|
2015-05-13 17:51:12 +03:00
|
|
|
|
2014-11-17 16:46:46 +01:00
|
|
|
self._url = ''
|
2018-06-26 13:12:00 +10:00
|
|
|
if url.hosts:
|
2014-12-08 16:48:36 +01:00
|
|
|
if url.transport.startswith('kombu+'):
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.warning('Selecting the kombu transport through the '
|
|
|
|
'transport url (%s) is a experimental feature '
|
|
|
|
'and this is not yet supported.',
|
2015-12-26 16:18:56 +08:00
|
|
|
url.transport)
|
2015-08-12 13:27:26 -04:00
|
|
|
if len(url.hosts) > 1:
|
|
|
|
random.shuffle(url.hosts)
|
2018-09-10 15:11:19 -06:00
|
|
|
transformed_urls = [
|
|
|
|
self._transform_transport_url(url, host)
|
|
|
|
for host in url.hosts]
|
|
|
|
self._url = ';'.join(transformed_urls)
|
2014-12-01 11:28:13 +01:00
|
|
|
elif url.transport.startswith('kombu+'):
|
|
|
|
# NOTE(sileht): url have a + but no hosts
|
|
|
|
# (like kombu+memory:///), pass it to kombu as-is
|
|
|
|
transport = url.transport.replace('kombu+', '')
|
2018-09-10 15:11:19 -06:00
|
|
|
self._url = "%s://" % transport
|
|
|
|
if url.virtual_host:
|
|
|
|
self._url += url.virtual_host
|
|
|
|
elif not url.hosts:
|
|
|
|
host = oslo_messaging.transport.TransportHost('')
|
|
|
|
self._url = self._transform_transport_url(
|
|
|
|
url, host, default_username='guest', default_password='guest',
|
|
|
|
default_hostname='localhost')
|
2014-03-07 10:46:17 +01:00
|
|
|
|
2014-11-27 14:46:52 +01:00
|
|
|
self._initial_pid = os.getpid()
|
|
|
|
|
2016-02-15 12:27:21 +01:00
|
|
|
self._consumers = {}
|
2016-04-29 05:55:55 +03:00
|
|
|
self._producer = None
|
2016-02-15 12:27:21 +01:00
|
|
|
self._new_tags = set()
|
|
|
|
self._active_tags = {}
|
|
|
|
self._tags = itertools.count(1)
|
|
|
|
|
2016-04-29 05:55:55 +03:00
|
|
|
# Set of exchanges and queues declared on the channel to avoid
|
|
|
|
# unnecessary redeclaration. This set is resetted each time
|
|
|
|
# the connection is resetted in Connection._set_current_channel
|
|
|
|
self._declared_exchanges = set()
|
|
|
|
self._declared_queues = set()
|
|
|
|
|
2014-12-08 10:52:45 +01:00
|
|
|
self._consume_loop_stopped = False
|
2014-11-17 16:46:46 +01:00
|
|
|
self.channel = None
|
2016-02-12 15:03:58 -05:00
|
|
|
self.purpose = purpose
|
2015-01-21 09:13:10 +01:00
|
|
|
|
|
|
|
# NOTE(sileht): if purpose is PURPOSE_LISTEN
|
|
|
|
# we don't need the lock because we don't
|
|
|
|
# have a heartbeat thread
|
2015-11-29 18:26:32 -05:00
|
|
|
if purpose == rpc_common.PURPOSE_SEND:
|
2015-01-21 09:13:10 +01:00
|
|
|
self._connection_lock = ConnectionLock()
|
|
|
|
else:
|
|
|
|
self._connection_lock = DummyConnectionLock()
|
|
|
|
|
2016-05-24 20:45:52 +03:00
|
|
|
self.connection_id = str(uuid.uuid4())
|
|
|
|
self.name = "%s:%d:%s" % (os.path.basename(sys.argv[0]),
|
|
|
|
os.getpid(),
|
|
|
|
self.connection_id)
|
2014-11-17 16:46:46 +01:00
|
|
|
self.connection = kombu.connection.Connection(
|
2015-02-10 13:32:22 +01:00
|
|
|
self._url, ssl=self._fetch_ssl_params(),
|
2015-05-13 17:51:12 +03:00
|
|
|
login_method=self.login_method,
|
|
|
|
heartbeat=self.heartbeat_timeout_threshold,
|
2015-11-23 17:27:24 +03:00
|
|
|
failover_strategy=self.kombu_failover_strategy,
|
2015-05-27 08:33:25 +02:00
|
|
|
transport_options={
|
|
|
|
'confirm_publish': True,
|
2016-05-24 20:45:52 +03:00
|
|
|
'client_properties': {
|
|
|
|
'capabilities': {
|
|
|
|
'authentication_failure_close': True,
|
|
|
|
'connection.blocked': True,
|
|
|
|
'consumer_cancel_notify': True
|
|
|
|
},
|
|
|
|
'connection_name': self.name},
|
2015-05-27 08:33:25 +02:00
|
|
|
'on_blocked': self._on_connection_blocked,
|
|
|
|
'on_unblocked': self._on_connection_unblocked,
|
|
|
|
},
|
|
|
|
)
|
2014-11-17 16:46:46 +01:00
|
|
|
|
2016-05-24 20:45:52 +03:00
|
|
|
LOG.debug('[%(connection_id)s] Connecting to AMQP server on'
|
|
|
|
' %(hostname)s:%(port)s',
|
|
|
|
self._get_connection_info())
|
2015-01-21 09:13:10 +01:00
|
|
|
|
|
|
|
# NOTE(sileht): kombu recommend to run heartbeat_check every
|
|
|
|
# seconds, but we use a lock around the kombu connection
|
|
|
|
# so, to not lock to much this lock to most of the time do nothing
|
|
|
|
# expected waiting the events drain, we start heartbeat_check and
|
2015-09-24 17:31:53 +08:00
|
|
|
# retrieve the server heartbeat packet only two times more than
|
2015-01-21 09:13:10 +01:00
|
|
|
# the minimum required for the heartbeat works
|
2019-06-17 17:58:47 +02:00
|
|
|
# (heartbeat_timeout/heartbeat_rate/2.0, default kombu
|
2015-01-21 09:13:10 +01:00
|
|
|
# heartbeat_rate is 2)
|
|
|
|
self._heartbeat_wait_timeout = (
|
2015-05-13 17:51:12 +03:00
|
|
|
float(self.heartbeat_timeout_threshold) /
|
|
|
|
float(self.heartbeat_rate) / 2.0)
|
2015-01-21 09:13:10 +01:00
|
|
|
self._heartbeat_support_log_emitted = False
|
|
|
|
|
2014-11-17 16:46:46 +01:00
|
|
|
# NOTE(sileht): just ensure the connection is setuped at startup
|
2017-01-03 14:39:21 +00:00
|
|
|
with self._connection_lock:
|
|
|
|
self.ensure_connection()
|
2015-01-21 09:13:10 +01:00
|
|
|
|
|
|
|
# NOTE(sileht): if purpose is PURPOSE_LISTEN
|
|
|
|
# the consume code does the heartbeat stuff
|
|
|
|
# we don't need a thread
|
2015-05-26 14:36:23 -04:00
|
|
|
self._heartbeat_thread = None
|
2015-11-29 18:26:32 -05:00
|
|
|
if purpose == rpc_common.PURPOSE_SEND:
|
2015-01-21 09:13:10 +01:00
|
|
|
self._heartbeat_start()
|
|
|
|
|
2016-05-24 20:45:52 +03:00
|
|
|
LOG.debug('[%(connection_id)s] Connected to AMQP server on '
|
|
|
|
'%(hostname)s:%(port)s via [%(transport)s] client with'
|
|
|
|
' port %(client_port)s.',
|
|
|
|
self._get_connection_info())
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2015-09-24 17:31:53 +08:00
|
|
|
# NOTE(sileht): value chosen according the best practice from kombu
|
2015-01-21 10:45:50 +01:00
|
|
|
# http://kombu.readthedocs.org/en/latest/reference/kombu.common.html#kombu.common.eventloop
|
2019-06-17 17:58:47 +02:00
|
|
|
# For heartbeat, we can set a bigger timeout, and check we receive the
|
2015-05-01 13:12:38 +02:00
|
|
|
# heartbeat packets regulary
|
|
|
|
if self._heartbeat_supported_and_enabled():
|
|
|
|
self._poll_timeout = self._heartbeat_wait_timeout
|
|
|
|
else:
|
|
|
|
self._poll_timeout = 1
|
2015-01-21 10:45:50 +01:00
|
|
|
|
2014-12-01 11:28:13 +01:00
|
|
|
if self._url.startswith('memory://'):
|
2014-11-17 16:46:46 +01:00
|
|
|
# Kludge to speed up tests.
|
|
|
|
self.connection.transport.polling_interval = 0.0
|
2015-04-30 23:33:39 +02:00
|
|
|
# Fixup logging
|
|
|
|
self.connection.hostname = "memory_driver"
|
|
|
|
self.connection.port = 1234
|
2015-01-21 10:45:50 +01:00
|
|
|
self._poll_timeout = 0.05
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2014-03-04 06:23:35 -08:00
|
|
|
# FIXME(markmc): use oslo sslutils when it is available as a library
|
|
|
|
_SSL_PROTOCOLS = {
|
|
|
|
"tlsv1": ssl.PROTOCOL_TLSv1,
|
2014-11-21 17:40:46 +08:00
|
|
|
"sslv23": ssl.PROTOCOL_SSLv23
|
2014-03-04 06:23:35 -08:00
|
|
|
}
|
|
|
|
|
2014-11-25 10:59:05 -06:00
|
|
|
_OPTIONAL_PROTOCOLS = {
|
|
|
|
'sslv2': 'PROTOCOL_SSLv2',
|
|
|
|
'sslv3': 'PROTOCOL_SSLv3',
|
|
|
|
'tlsv1_1': 'PROTOCOL_TLSv1_1',
|
|
|
|
'tlsv1_2': 'PROTOCOL_TLSv1_2',
|
|
|
|
}
|
|
|
|
for protocol in _OPTIONAL_PROTOCOLS:
|
|
|
|
try:
|
|
|
|
_SSL_PROTOCOLS[protocol] = getattr(ssl,
|
|
|
|
_OPTIONAL_PROTOCOLS[protocol])
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2014-03-04 06:23:35 -08:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def validate_ssl_version(cls, version):
|
|
|
|
key = version.lower()
|
|
|
|
try:
|
|
|
|
return cls._SSL_PROTOCOLS[key]
|
|
|
|
except KeyError:
|
2019-04-11 10:47:24 +02:00
|
|
|
raise RuntimeError("Invalid SSL version : %s" % version)
|
2014-03-04 06:23:35 -08:00
|
|
|
|
2018-09-10 15:11:19 -06:00
|
|
|
def _transform_transport_url(self, url, host, default_username='',
|
|
|
|
default_password='', default_hostname=''):
|
|
|
|
transport = url.transport.replace('kombu+', '')
|
|
|
|
transport = transport.replace('rabbit', 'amqp')
|
|
|
|
return '%s://%s:%s@%s:%s/%s' % (
|
|
|
|
transport,
|
|
|
|
parse.quote(host.username or default_username),
|
|
|
|
parse.quote(host.password or default_password),
|
|
|
|
self._parse_url_hostname(host.hostname) or default_hostname,
|
|
|
|
str(host.port or 5672),
|
2018-10-18 11:41:23 -04:00
|
|
|
url.virtual_host or '')
|
2018-09-10 15:11:19 -06:00
|
|
|
|
2015-03-19 15:09:52 +01:00
|
|
|
def _parse_url_hostname(self, hostname):
|
|
|
|
"""Handles hostname returned from urlparse and checks whether it's
|
|
|
|
ipaddress. If it's ipaddress it ensures that it has brackets for IPv6.
|
|
|
|
"""
|
|
|
|
return '[%s]' % hostname if ':' in hostname else hostname
|
|
|
|
|
2013-07-23 16:28:15 +01:00
|
|
|
def _fetch_ssl_params(self):
|
|
|
|
"""Handles fetching what ssl params should be used for the connection
|
|
|
|
(if any).
|
|
|
|
"""
|
2017-02-27 13:43:48 +02:00
|
|
|
if self.ssl:
|
2015-02-10 13:32:22 +01:00
|
|
|
ssl_params = dict()
|
|
|
|
|
|
|
|
# http://docs.python.org/library/ssl.html - ssl.wrap_socket
|
2017-02-27 13:43:48 +02:00
|
|
|
if self.ssl_version:
|
2015-02-10 13:32:22 +01:00
|
|
|
ssl_params['ssl_version'] = self.validate_ssl_version(
|
2017-02-27 13:43:48 +02:00
|
|
|
self.ssl_version)
|
|
|
|
if self.ssl_key_file:
|
|
|
|
ssl_params['keyfile'] = self.ssl_key_file
|
|
|
|
if self.ssl_cert_file:
|
|
|
|
ssl_params['certfile'] = self.ssl_cert_file
|
|
|
|
if self.ssl_ca_file:
|
|
|
|
ssl_params['ca_certs'] = self.ssl_ca_file
|
2015-02-10 13:32:22 +01:00
|
|
|
# We might want to allow variations in the
|
|
|
|
# future with this?
|
|
|
|
ssl_params['cert_reqs'] = ssl.CERT_REQUIRED
|
|
|
|
return ssl_params or True
|
|
|
|
return False
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2015-05-27 08:33:25 +02:00
|
|
|
@staticmethod
|
|
|
|
def _on_connection_blocked(reason):
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.error("The broker has blocked the connection: %s", reason)
|
2015-05-27 08:33:25 +02:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _on_connection_unblocked():
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.info("The broker has unblocked the connection")
|
2015-05-27 08:33:25 +02:00
|
|
|
|
2015-01-21 09:13:10 +01:00
|
|
|
def ensure_connection(self):
|
2015-12-04 14:57:03 +01:00
|
|
|
# NOTE(sileht): we reset the channel and ensure
|
|
|
|
# the kombu underlying connection works
|
2018-11-05 16:02:06 -05:00
|
|
|
def on_error(exc, interval):
|
|
|
|
LOG.error("Connection failed: %s (retrying in %s seconds)",
|
|
|
|
str(exc), interval)
|
|
|
|
|
2015-12-04 14:57:03 +01:00
|
|
|
self._set_current_channel(None)
|
2018-11-05 16:02:06 -05:00
|
|
|
self.connection.ensure_connection(errback=on_error)
|
|
|
|
self._set_current_channel(self.connection.channel())
|
2016-03-17 15:25:38 +01:00
|
|
|
self.set_transport_socket_timeout()
|
2015-01-21 09:13:10 +01:00
|
|
|
|
2015-03-18 07:59:19 +01:00
|
|
|
def ensure(self, method, retry=None,
|
|
|
|
recoverable_error_callback=None, error_callback=None,
|
2014-11-17 16:46:46 +01:00
|
|
|
timeout_is_error=True):
|
|
|
|
"""Will retry up to retry number of times.
|
2018-09-10 15:11:19 -06:00
|
|
|
retry = None or -1 means to retry forever
|
2014-02-21 11:50:45 +01:00
|
|
|
retry = 0 means no retry
|
|
|
|
retry = N means N retries
|
2015-01-21 09:13:10 +01:00
|
|
|
|
|
|
|
NOTE(sileht): Must be called within the connection lock
|
2013-07-23 16:28:15 +01:00
|
|
|
"""
|
|
|
|
|
2014-11-27 14:46:52 +01:00
|
|
|
current_pid = os.getpid()
|
|
|
|
if self._initial_pid != current_pid:
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.warning("Process forked after connection established! "
|
|
|
|
"This can result in unpredictable behavior. "
|
|
|
|
"See: https://docs.openstack.org/oslo.messaging/"
|
|
|
|
"latest/reference/transport.html")
|
2014-11-27 14:46:52 +01:00
|
|
|
self._initial_pid = current_pid
|
|
|
|
|
2014-02-21 11:50:45 +01:00
|
|
|
if retry is None or retry < 0:
|
2018-09-10 15:11:19 -06:00
|
|
|
retry = float('inf')
|
2014-02-21 11:50:45 +01:00
|
|
|
|
2014-11-17 16:46:46 +01:00
|
|
|
def on_error(exc, interval):
|
2016-05-24 20:45:52 +03:00
|
|
|
LOG.debug("[%s] Received recoverable error from kombu:"
|
|
|
|
% self.connection_id,
|
2015-03-18 07:59:19 +01:00
|
|
|
exc_info=True)
|
|
|
|
|
|
|
|
recoverable_error_callback and recoverable_error_callback(exc)
|
2014-02-21 11:50:45 +01:00
|
|
|
|
2015-05-13 17:51:12 +03:00
|
|
|
interval = (self.kombu_reconnect_delay + interval
|
|
|
|
if self.kombu_reconnect_delay > 0
|
2015-01-28 08:57:21 +01:00
|
|
|
else interval)
|
2014-12-01 23:27:46 +01:00
|
|
|
|
2014-12-08 16:48:36 +01:00
|
|
|
info = {'err_str': exc, 'sleep_time': interval}
|
2018-07-06 11:24:40 -04:00
|
|
|
info.update(self._get_connection_info(conn_error=True))
|
2014-11-17 16:46:46 +01:00
|
|
|
|
|
|
|
if 'Socket closed' in six.text_type(exc):
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.error('[%(connection_id)s] AMQP server'
|
|
|
|
' %(hostname)s:%(port)s closed'
|
|
|
|
' the connection. Check login credentials:'
|
|
|
|
' %(err_str)s', info)
|
2014-02-21 11:50:45 +01:00
|
|
|
else:
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.error('[%(connection_id)s] AMQP server on '
|
|
|
|
'%(hostname)s:%(port)s is unreachable: '
|
|
|
|
'%(err_str)s. Trying again in '
|
|
|
|
'%(sleep_time)d seconds.', info)
|
2014-11-17 16:46:46 +01:00
|
|
|
|
|
|
|
# XXX(nic): when reconnecting to a RabbitMQ cluster
|
|
|
|
# with mirrored queues in use, the attempt to release the
|
|
|
|
# connection can hang "indefinitely" somewhere deep down
|
|
|
|
# in Kombu. Blocking the thread for a bit prior to
|
|
|
|
# release seems to kludge around the problem where it is
|
|
|
|
# otherwise reproduceable.
|
|
|
|
# TODO(sileht): Check if this is useful since we
|
|
|
|
# use kombu for HA connection, the interval_step
|
|
|
|
# should sufficient, because the underlying kombu transport
|
|
|
|
# connection object freed.
|
2015-05-13 17:51:12 +03:00
|
|
|
if self.kombu_reconnect_delay > 0:
|
2015-06-22 14:36:11 -04:00
|
|
|
LOG.trace('Delaying reconnect for %1.1f seconds ...',
|
|
|
|
self.kombu_reconnect_delay)
|
2015-05-13 17:51:12 +03:00
|
|
|
time.sleep(self.kombu_reconnect_delay)
|
2014-11-17 16:46:46 +01:00
|
|
|
|
2014-12-01 23:27:46 +01:00
|
|
|
def on_reconnection(new_channel):
|
|
|
|
"""Callback invoked when the kombu reconnects and creates
|
|
|
|
a new channel, we use it the reconfigure our consumers.
|
|
|
|
"""
|
2015-01-06 15:11:55 +01:00
|
|
|
self._set_current_channel(new_channel)
|
2016-11-10 14:31:32 +03:00
|
|
|
self.set_transport_socket_timeout()
|
2014-12-01 23:27:46 +01:00
|
|
|
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.info('[%(connection_id)s] Reconnected to AMQP server on '
|
|
|
|
'%(hostname)s:%(port)s via [%(transport)s] client '
|
|
|
|
'with port %(client_port)s.',
|
2016-05-24 20:45:52 +03:00
|
|
|
self._get_connection_info())
|
2014-12-02 15:48:34 +01:00
|
|
|
|
2015-01-06 15:11:55 +01:00
|
|
|
def execute_method(channel):
|
|
|
|
self._set_current_channel(channel)
|
|
|
|
method()
|
|
|
|
|
2014-11-17 16:46:46 +01:00
|
|
|
try:
|
|
|
|
autoretry_method = self.connection.autoretry(
|
2015-01-06 15:11:55 +01:00
|
|
|
execute_method, channel=self.channel,
|
2014-11-17 16:46:46 +01:00
|
|
|
max_retries=retry,
|
|
|
|
errback=on_error,
|
|
|
|
interval_start=self.interval_start or 1,
|
|
|
|
interval_step=self.interval_stepping,
|
2016-01-10 19:05:53 +02:00
|
|
|
interval_max=self.interval_max,
|
2015-12-24 15:52:59 +08:00
|
|
|
on_revive=on_reconnection)
|
2014-11-17 16:46:46 +01:00
|
|
|
ret, channel = autoretry_method()
|
2015-01-06 15:11:55 +01:00
|
|
|
self._set_current_channel(channel)
|
2014-11-17 16:46:46 +01:00
|
|
|
return ret
|
2017-07-24 13:36:17 -04:00
|
|
|
except rpc_amqp.AMQPDestinationNotFound:
|
|
|
|
# NOTE(sileht): we must reraise this without
|
|
|
|
# trigger error_callback
|
|
|
|
raise
|
2019-06-27 13:13:47 +02:00
|
|
|
except exceptions.MessageUndeliverable:
|
|
|
|
# NOTE(gsantomaggio): we must reraise this without
|
|
|
|
# trigger error_callback
|
|
|
|
raise
|
2017-07-24 13:36:17 -04:00
|
|
|
except Exception as exc:
|
2015-03-18 07:59:19 +01:00
|
|
|
error_callback and error_callback(exc)
|
2015-01-06 15:11:55 +01:00
|
|
|
self._set_current_channel(None)
|
2014-11-17 16:46:46 +01:00
|
|
|
# NOTE(sileht): number of retry exceeded and the connection
|
|
|
|
# is still broken
|
2015-05-06 11:11:03 +02:00
|
|
|
info = {'err_str': exc, 'retry': retry}
|
|
|
|
info.update(self.connection.info())
|
2019-04-11 10:47:24 +02:00
|
|
|
msg = ('Unable to connect to AMQP server on '
|
|
|
|
'%(hostname)s:%(port)s after %(retry)s '
|
|
|
|
'tries: %(err_str)s' % info)
|
2014-11-17 16:46:46 +01:00
|
|
|
LOG.error(msg)
|
|
|
|
raise exceptions.MessageDeliveryFailure(msg)
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2019-06-27 13:13:47 +02:00
|
|
|
@staticmethod
|
|
|
|
def on_return(exception, exchange, routing_key, message):
|
|
|
|
raise exceptions.MessageUndeliverable(exception, exchange, routing_key,
|
|
|
|
message)
|
|
|
|
|
2015-01-06 15:11:55 +01:00
|
|
|
def _set_current_channel(self, new_channel):
|
2015-01-21 09:13:10 +01:00
|
|
|
"""Change the channel to use.
|
|
|
|
|
|
|
|
NOTE(sileht): Must be called within the connection lock
|
|
|
|
"""
|
2016-02-12 15:03:58 -05:00
|
|
|
if new_channel == self.channel:
|
|
|
|
return
|
|
|
|
|
|
|
|
if self.channel is not None:
|
2016-04-29 05:55:55 +03:00
|
|
|
self._declared_queues.clear()
|
|
|
|
self._declared_exchanges.clear()
|
2015-01-06 15:11:55 +01:00
|
|
|
self.connection.maybe_close_channel(self.channel)
|
2016-02-12 15:03:58 -05:00
|
|
|
|
2015-01-06 15:11:55 +01:00
|
|
|
self.channel = new_channel
|
|
|
|
|
2016-04-29 05:55:55 +03:00
|
|
|
if new_channel is not None:
|
|
|
|
if self.purpose == rpc_common.PURPOSE_LISTEN:
|
|
|
|
self._set_qos(new_channel)
|
2019-06-27 13:13:47 +02:00
|
|
|
self._producer = kombu.messaging.Producer(new_channel,
|
|
|
|
on_return=self.on_return)
|
2016-08-04 15:18:25 +03:00
|
|
|
for consumer in self._consumers:
|
|
|
|
consumer.declare(self)
|
2016-02-12 15:03:58 -05:00
|
|
|
|
2016-01-19 22:59:38 -05:00
|
|
|
def _set_qos(self, channel):
|
|
|
|
"""Set QoS prefetch count on the channel"""
|
2016-02-12 15:03:58 -05:00
|
|
|
if self.rabbit_qos_prefetch_count > 0:
|
2016-01-19 22:59:38 -05:00
|
|
|
channel.basic_qos(0,
|
|
|
|
self.rabbit_qos_prefetch_count,
|
|
|
|
False)
|
|
|
|
|
2013-07-23 16:28:15 +01:00
|
|
|
def close(self):
|
|
|
|
"""Close/release this connection."""
|
2015-01-21 09:13:10 +01:00
|
|
|
self._heartbeat_stop()
|
2014-02-21 11:50:45 +01:00
|
|
|
if self.connection:
|
2018-10-28 17:29:56 +01:00
|
|
|
for consumer in six.moves.filter(lambda c: c.type == 'fanout',
|
|
|
|
self._consumers):
|
|
|
|
LOG.debug('[connection close] Deleting fanout '
|
|
|
|
'queue: %s ' % consumer.queue.name)
|
|
|
|
consumer.queue.delete()
|
2015-01-06 15:11:55 +01:00
|
|
|
self._set_current_channel(None)
|
2014-02-21 11:50:45 +01:00
|
|
|
self.connection.release()
|
|
|
|
self.connection = None
|
2013-07-23 16:28:15 +01:00
|
|
|
|
|
|
|
def reset(self):
|
|
|
|
"""Reset a connection so it can be used again."""
|
2015-01-21 09:13:10 +01:00
|
|
|
with self._connection_lock:
|
2015-03-18 08:31:32 +01:00
|
|
|
try:
|
2016-02-15 12:27:21 +01:00
|
|
|
for consumer, tag in self._consumers.items():
|
2015-05-12 14:25:47 +03:00
|
|
|
consumer.cancel(tag=tag)
|
2017-02-16 21:50:50 +00:00
|
|
|
except kombu.exceptions.OperationalError:
|
2015-03-18 08:31:32 +01:00
|
|
|
self.ensure_connection()
|
2016-02-15 12:27:21 +01:00
|
|
|
self._consumers.clear()
|
|
|
|
self._active_tags.clear()
|
|
|
|
self._new_tags.clear()
|
|
|
|
self._tags = itertools.count(1)
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2015-01-21 09:13:10 +01:00
|
|
|
def _heartbeat_supported_and_enabled(self):
|
2015-05-13 17:51:12 +03:00
|
|
|
if self.heartbeat_timeout_threshold <= 0:
|
2015-01-21 09:13:10 +01:00
|
|
|
return False
|
|
|
|
|
|
|
|
if self.connection.supports_heartbeats:
|
|
|
|
return True
|
|
|
|
elif not self._heartbeat_support_log_emitted:
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.warning("Heartbeat support requested but it is not "
|
|
|
|
"supported by the kombu driver or the broker")
|
2015-01-21 09:13:10 +01:00
|
|
|
self._heartbeat_support_log_emitted = True
|
|
|
|
return False
|
|
|
|
|
2016-03-17 15:25:38 +01:00
|
|
|
def set_transport_socket_timeout(self, timeout=None):
|
2015-05-01 13:12:38 +02:00
|
|
|
# NOTE(sileht): they are some case where the heartbeat check
|
|
|
|
# or the producer.send return only when the system socket
|
|
|
|
# timeout if reach. kombu doesn't allow use to customise this
|
|
|
|
# timeout so for py-amqp we tweak ourself
|
2016-02-02 00:26:32 +03:00
|
|
|
# NOTE(dmitryme): Current approach works with amqp==1.4.9 and
|
|
|
|
# kombu==3.0.33. Once the commit below is released, we should
|
|
|
|
# try to set the socket timeout in the constructor:
|
|
|
|
# https://github.com/celery/py-amqp/pull/64
|
2016-03-17 15:25:38 +01:00
|
|
|
|
|
|
|
heartbeat_timeout = self.heartbeat_timeout_threshold
|
|
|
|
if self._heartbeat_supported_and_enabled():
|
|
|
|
# NOTE(sileht): we are supposed to send heartbeat every
|
|
|
|
# heartbeat_timeout, no need to wait more otherwise will
|
|
|
|
# disconnect us, so raise timeout earlier ourself
|
|
|
|
if timeout is None:
|
|
|
|
timeout = heartbeat_timeout
|
|
|
|
else:
|
|
|
|
timeout = min(heartbeat_timeout, timeout)
|
|
|
|
|
2016-02-02 00:26:32 +03:00
|
|
|
try:
|
|
|
|
sock = self.channel.connection.sock
|
|
|
|
except AttributeError as e:
|
|
|
|
# Level is set to debug because otherwise we would spam the logs
|
2016-05-24 20:45:52 +03:00
|
|
|
LOG.debug('[%s] Failed to get socket attribute: %s'
|
|
|
|
% (self.connection_id, str(e)))
|
2016-03-17 15:25:38 +01:00
|
|
|
else:
|
2015-05-01 13:12:38 +02:00
|
|
|
sock.settimeout(timeout)
|
2016-04-06 19:23:22 +03:00
|
|
|
# TCP_USER_TIMEOUT is not defined on Windows and Mac OS X
|
|
|
|
if sys.platform != 'win32' and sys.platform != 'darwin':
|
2016-04-20 16:08:17 +00:00
|
|
|
try:
|
|
|
|
timeout = timeout * 1000 if timeout is not None else 0
|
2016-05-06 15:36:18 +03:00
|
|
|
# NOTE(gdavoian): only integers and strings are allowed
|
|
|
|
# as socket options' values, and TCP_USER_TIMEOUT option
|
|
|
|
# can take only integer values, so we round-up the timeout
|
|
|
|
# to the nearest integer in order to ensure that the
|
|
|
|
# connection is not broken before the expected timeout
|
2016-04-20 16:08:17 +00:00
|
|
|
sock.setsockopt(socket.IPPROTO_TCP,
|
|
|
|
TCP_USER_TIMEOUT,
|
2016-05-06 15:36:18 +03:00
|
|
|
int(math.ceil(timeout)))
|
2016-04-20 16:08:17 +00:00
|
|
|
except socket.error as error:
|
|
|
|
code = error[0]
|
|
|
|
# TCP_USER_TIMEOUT not defined on kernels <2.6.37
|
|
|
|
if code != errno.ENOPROTOOPT:
|
|
|
|
raise
|
2016-03-17 15:25:38 +01:00
|
|
|
|
|
|
|
@contextlib.contextmanager
|
|
|
|
def _transport_socket_timeout(self, timeout):
|
|
|
|
self.set_transport_socket_timeout(timeout)
|
2015-05-01 13:12:38 +02:00
|
|
|
yield
|
2016-03-17 15:25:38 +01:00
|
|
|
self.set_transport_socket_timeout()
|
2015-05-01 13:12:38 +02:00
|
|
|
|
|
|
|
def _heartbeat_check(self):
|
2016-02-04 07:02:22 +05:30
|
|
|
# NOTE(sileht): we are supposed to send at least one heartbeat
|
2015-05-01 13:12:38 +02:00
|
|
|
# every heartbeat_timeout_threshold, so no need to way more
|
2016-03-17 15:25:38 +01:00
|
|
|
self.connection.heartbeat_check(rate=self.heartbeat_rate)
|
2015-05-01 13:12:38 +02:00
|
|
|
|
2015-01-21 09:13:10 +01:00
|
|
|
def _heartbeat_start(self):
|
|
|
|
if self._heartbeat_supported_and_enabled():
|
2019-06-04 17:45:59 +02:00
|
|
|
self._heartbeat_exit_event = threading.Event()
|
2015-01-21 09:13:10 +01:00
|
|
|
self._heartbeat_thread = threading.Thread(
|
2019-05-24 22:02:19 +02:00
|
|
|
target=self._heartbeat_thread_job, name="Rabbit-heartbeat")
|
2015-01-21 09:13:10 +01:00
|
|
|
self._heartbeat_thread.daemon = True
|
|
|
|
self._heartbeat_thread.start()
|
|
|
|
else:
|
|
|
|
self._heartbeat_thread = None
|
|
|
|
|
|
|
|
def _heartbeat_stop(self):
|
|
|
|
if self._heartbeat_thread is not None:
|
|
|
|
self._heartbeat_exit_event.set()
|
|
|
|
self._heartbeat_thread.join()
|
|
|
|
self._heartbeat_thread = None
|
|
|
|
|
|
|
|
def _heartbeat_thread_job(self):
|
|
|
|
"""Thread that maintains inactive connections
|
|
|
|
"""
|
2019-05-03 00:55:56 +02:00
|
|
|
# NOTE(hberaud): Python2 doesn't have ConnectionRefusedError
|
|
|
|
# defined so to switch connections destination on failure
|
|
|
|
# with python2 and python3 we need to wrapp adapt connection refused
|
|
|
|
try:
|
|
|
|
ConnectRefuseError = ConnectionRefusedError
|
|
|
|
except NameError:
|
|
|
|
ConnectRefuseError = socket.error
|
|
|
|
|
2015-01-21 09:13:10 +01:00
|
|
|
while not self._heartbeat_exit_event.is_set():
|
|
|
|
with self._connection_lock.for_heartbeat():
|
|
|
|
|
|
|
|
try:
|
|
|
|
try:
|
2015-05-01 13:12:38 +02:00
|
|
|
self._heartbeat_check()
|
2015-01-21 09:13:10 +01:00
|
|
|
# NOTE(sileht): We need to drain event to receive
|
|
|
|
# heartbeat from the broker but don't hold the
|
|
|
|
# connection too much times. In amqpdriver a connection
|
2016-03-29 10:59:12 +07:00
|
|
|
# is used exclusively for read or for write, so we have
|
2015-01-21 09:13:10 +01:00
|
|
|
# to do this for connection used for write drain_events
|
|
|
|
# already do that for other connection
|
|
|
|
try:
|
|
|
|
self.connection.drain_events(timeout=0.001)
|
|
|
|
except socket.timeout:
|
|
|
|
pass
|
2019-05-03 00:55:56 +02:00
|
|
|
# NOTE(hberaud): In a clustered rabbitmq when
|
|
|
|
# a node disappears, we get a ConnectionRefusedError
|
|
|
|
# because the socket get disconnected.
|
|
|
|
# The socket access yields a OSError because the heartbeat
|
|
|
|
# tries to reach an unreachable host (No route to host).
|
|
|
|
# Catch these exceptions to ensure that we call
|
|
|
|
# ensure_connection for switching the
|
|
|
|
# connection destination.
|
2017-11-14 17:53:32 +01:00
|
|
|
except (socket.timeout,
|
2019-05-03 00:55:56 +02:00
|
|
|
ConnectRefuseError,
|
|
|
|
OSError,
|
2017-11-14 17:53:32 +01:00
|
|
|
kombu.exceptions.OperationalError) as exc:
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.info("A recoverable connection/channel error "
|
|
|
|
"occurred, trying to reconnect: %s", exc)
|
2015-03-19 09:33:00 +01:00
|
|
|
self.ensure_connection()
|
2015-01-21 09:13:10 +01:00
|
|
|
except Exception:
|
2019-06-17 17:58:47 +02:00
|
|
|
LOG.warning("Unexpected error during heartbeat "
|
2019-04-11 10:47:24 +02:00
|
|
|
"thread processing, retrying...")
|
2015-03-18 14:19:47 -04:00
|
|
|
LOG.debug('Exception', exc_info=True)
|
2015-01-21 09:13:10 +01:00
|
|
|
|
|
|
|
self._heartbeat_exit_event.wait(
|
|
|
|
timeout=self._heartbeat_wait_timeout)
|
|
|
|
self._heartbeat_exit_event.clear()
|
|
|
|
|
2015-04-30 17:46:42 +02:00
|
|
|
def declare_consumer(self, consumer):
|
2013-07-23 16:28:15 +01:00
|
|
|
"""Create a Consumer using the class that was passed in and
|
|
|
|
add it to our list of consumers
|
|
|
|
"""
|
|
|
|
|
|
|
|
def _connect_error(exc):
|
2015-04-30 17:46:42 +02:00
|
|
|
log_info = {'topic': consumer.routing_key, 'err_str': exc}
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.error("Failed to declare consumer for topic '%(topic)s': "
|
|
|
|
"%(err_str)s", log_info)
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2015-01-06 15:11:55 +01:00
|
|
|
def _declare_consumer():
|
2015-05-01 00:24:46 +02:00
|
|
|
consumer.declare(self)
|
2016-02-15 12:27:21 +01:00
|
|
|
tag = self._active_tags.get(consumer.queue_name)
|
|
|
|
if tag is None:
|
|
|
|
tag = next(self._tags)
|
|
|
|
self._active_tags[consumer.queue_name] = tag
|
|
|
|
self._new_tags.add(tag)
|
|
|
|
|
|
|
|
self._consumers[consumer] = tag
|
2013-07-23 16:28:15 +01:00
|
|
|
return consumer
|
|
|
|
|
2015-01-21 09:13:10 +01:00
|
|
|
with self._connection_lock:
|
2015-03-18 07:59:19 +01:00
|
|
|
return self.ensure(_declare_consumer,
|
|
|
|
error_callback=_connect_error)
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2015-04-30 08:56:20 +02:00
|
|
|
def consume(self, timeout=None):
|
|
|
|
"""Consume from all queues/consumers."""
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2014-12-26 20:22:21 +08:00
|
|
|
timer = rpc_common.DecayingTimer(duration=timeout)
|
|
|
|
timer.start()
|
2014-12-01 23:27:46 +01:00
|
|
|
|
Suppress excessive debug logs when consume rabbit
If using rabbitmq as rpc backend, oslo.messaging generates large amount
of redundant timeout debug logs (several logs per second on multiple
openstack services, such as nova, heat, cinder), in format of 'Timed out
waiting for RPC response: Timeout while waiting on RPC response - topic:
"<unknown>", RPC method: "<unknown>" info: "<unknown>'. It's because
each socket timeout exception is raised to multiple levels of error
recovery callback functions then logged repeatedly.
However, the accompanying value of socket.timeout exception is currently
always “timed out”. Besides, oslo.messaging has implemented retry
mechanism to recover socket timeout failure. Therefore, IMO those logs
should be suppressed, even if at debug level, to save disk space and
make debugging more convenient.
Change-Id: Iafc360f8d18871cff93e7fd721d793ecdef5f4a1
Closes-Bug: #1714558
2017-09-01 13:38:05 -04:00
|
|
|
def _raise_timeout():
|
2014-12-08 10:56:52 +01:00
|
|
|
raise rpc_common.Timeout()
|
2014-12-01 23:27:46 +01:00
|
|
|
|
2015-03-18 07:59:19 +01:00
|
|
|
def _recoverable_error_callback(exc):
|
2015-08-02 10:26:02 +02:00
|
|
|
if not isinstance(exc, rpc_common.Timeout):
|
2016-02-15 12:27:21 +01:00
|
|
|
self._new_tags = set(self._consumers.values())
|
Suppress excessive debug logs when consume rabbit
If using rabbitmq as rpc backend, oslo.messaging generates large amount
of redundant timeout debug logs (several logs per second on multiple
openstack services, such as nova, heat, cinder), in format of 'Timed out
waiting for RPC response: Timeout while waiting on RPC response - topic:
"<unknown>", RPC method: "<unknown>" info: "<unknown>'. It's because
each socket timeout exception is raised to multiple levels of error
recovery callback functions then logged repeatedly.
However, the accompanying value of socket.timeout exception is currently
always “timed out”. Besides, oslo.messaging has implemented retry
mechanism to recover socket timeout failure. Therefore, IMO those logs
should be suppressed, even if at debug level, to save disk space and
make debugging more convenient.
Change-Id: Iafc360f8d18871cff93e7fd721d793ecdef5f4a1
Closes-Bug: #1714558
2017-09-01 13:38:05 -04:00
|
|
|
timer.check_return(_raise_timeout)
|
2015-03-18 07:59:19 +01:00
|
|
|
|
|
|
|
def _error_callback(exc):
|
|
|
|
_recoverable_error_callback(exc)
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.error('Failed to consume message from queue: %s', exc)
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2015-01-06 15:11:55 +01:00
|
|
|
def _consume():
|
2015-09-24 17:31:53 +08:00
|
|
|
# NOTE(sileht): in case the acknowledgment or requeue of a
|
2015-05-05 10:29:22 +02:00
|
|
|
# message fail, the kombu transport can be disconnected
|
|
|
|
# In this case, we must redeclare our consumers, so raise
|
|
|
|
# a recoverable error to trigger the reconnection code.
|
|
|
|
if not self.connection.connected:
|
|
|
|
raise self.connection.recoverable_connection_errors[0]
|
|
|
|
|
2016-08-04 15:18:25 +03:00
|
|
|
while self._new_tags:
|
2016-02-15 12:27:21 +01:00
|
|
|
for consumer, tag in self._consumers.items():
|
|
|
|
if tag in self._new_tags:
|
2016-08-04 15:18:25 +03:00
|
|
|
consumer.consume(self, tag=tag)
|
|
|
|
self._new_tags.remove(tag)
|
2014-12-08 10:56:52 +01:00
|
|
|
|
2015-01-21 10:45:50 +01:00
|
|
|
poll_timeout = (self._poll_timeout if timeout is None
|
|
|
|
else min(timeout, self._poll_timeout))
|
2014-12-01 23:27:46 +01:00
|
|
|
while True:
|
2014-12-08 10:52:45 +01:00
|
|
|
if self._consume_loop_stopped:
|
2015-04-30 08:56:20 +02:00
|
|
|
return
|
2014-12-08 10:52:45 +01:00
|
|
|
|
2015-01-21 09:13:10 +01:00
|
|
|
if self._heartbeat_supported_and_enabled():
|
2015-05-01 13:12:38 +02:00
|
|
|
self._heartbeat_check()
|
|
|
|
|
2014-12-01 23:27:46 +01:00
|
|
|
try:
|
2015-04-30 08:56:20 +02:00
|
|
|
self.connection.drain_events(timeout=poll_timeout)
|
|
|
|
return
|
Suppress excessive debug logs when consume rabbit
If using rabbitmq as rpc backend, oslo.messaging generates large amount
of redundant timeout debug logs (several logs per second on multiple
openstack services, such as nova, heat, cinder), in format of 'Timed out
waiting for RPC response: Timeout while waiting on RPC response - topic:
"<unknown>", RPC method: "<unknown>" info: "<unknown>'. It's because
each socket timeout exception is raised to multiple levels of error
recovery callback functions then logged repeatedly.
However, the accompanying value of socket.timeout exception is currently
always “timed out”. Besides, oslo.messaging has implemented retry
mechanism to recover socket timeout failure. Therefore, IMO those logs
should be suppressed, even if at debug level, to save disk space and
make debugging more convenient.
Change-Id: Iafc360f8d18871cff93e7fd721d793ecdef5f4a1
Closes-Bug: #1714558
2017-09-01 13:38:05 -04:00
|
|
|
except socket.timeout:
|
2015-01-21 10:45:50 +01:00
|
|
|
poll_timeout = timer.check_return(
|
Suppress excessive debug logs when consume rabbit
If using rabbitmq as rpc backend, oslo.messaging generates large amount
of redundant timeout debug logs (several logs per second on multiple
openstack services, such as nova, heat, cinder), in format of 'Timed out
waiting for RPC response: Timeout while waiting on RPC response - topic:
"<unknown>", RPC method: "<unknown>" info: "<unknown>'. It's because
each socket timeout exception is raised to multiple levels of error
recovery callback functions then logged repeatedly.
However, the accompanying value of socket.timeout exception is currently
always “timed out”. Besides, oslo.messaging has implemented retry
mechanism to recover socket timeout failure. Therefore, IMO those logs
should be suppressed, even if at debug level, to save disk space and
make debugging more convenient.
Change-Id: Iafc360f8d18871cff93e7fd721d793ecdef5f4a1
Closes-Bug: #1714558
2017-09-01 13:38:05 -04:00
|
|
|
_raise_timeout, maximum=self._poll_timeout)
|
2016-12-09 18:31:06 +00:00
|
|
|
except self.connection.channel_errors as exc:
|
|
|
|
if exc.code == 406 and exc.method_name == 'Basic.ack':
|
|
|
|
# NOTE(gordc): occasionally multiple workers will grab
|
|
|
|
# same message and acknowledge it. if it happens, meh.
|
|
|
|
raise self.connection.recoverable_channel_errors[0]
|
|
|
|
raise
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2015-04-30 08:56:20 +02:00
|
|
|
with self._connection_lock:
|
|
|
|
self.ensure(_consume,
|
|
|
|
recoverable_error_callback=_recoverable_error_callback,
|
|
|
|
error_callback=_error_callback)
|
2015-03-18 07:59:19 +01:00
|
|
|
|
2015-05-05 14:37:58 +02:00
|
|
|
def stop_consuming(self):
|
|
|
|
self._consume_loop_stopped = True
|
2013-07-23 16:28:15 +01:00
|
|
|
|
|
|
|
def declare_direct_consumer(self, topic, callback):
|
|
|
|
"""Create a 'direct' queue.
|
|
|
|
In nova's use, this is generally a msg_id queue used for
|
|
|
|
responses for call/multicall
|
|
|
|
"""
|
2015-04-30 17:46:42 +02:00
|
|
|
|
2019-07-04 16:08:45 +04:00
|
|
|
consumer = Consumer(exchange_name='', # using default exchange
|
2015-04-30 17:46:42 +02:00
|
|
|
queue_name=topic,
|
2019-07-04 16:08:45 +04:00
|
|
|
routing_key='',
|
2015-04-30 17:46:42 +02:00
|
|
|
type='direct',
|
|
|
|
durable=False,
|
2019-07-04 16:08:45 +04:00
|
|
|
exchange_auto_delete=False,
|
2015-11-20 17:25:58 -05:00
|
|
|
queue_auto_delete=False,
|
2015-05-13 17:51:12 +03:00
|
|
|
callback=callback,
|
2015-11-20 17:25:58 -05:00
|
|
|
rabbit_ha_queues=self.rabbit_ha_queues,
|
|
|
|
rabbit_queue_ttl=self.rabbit_transient_queues_ttl)
|
2015-04-30 17:46:42 +02:00
|
|
|
|
|
|
|
self.declare_consumer(consumer)
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2014-04-24 12:04:20 +02:00
|
|
|
def declare_topic_consumer(self, exchange_name, topic, callback=None,
|
|
|
|
queue_name=None):
|
2013-07-23 16:28:15 +01:00
|
|
|
"""Create a 'topic' consumer."""
|
2015-05-13 17:51:12 +03:00
|
|
|
consumer = Consumer(exchange_name=exchange_name,
|
2015-04-30 17:46:42 +02:00
|
|
|
queue_name=queue_name or topic,
|
|
|
|
routing_key=topic,
|
|
|
|
type='topic',
|
2015-05-13 17:51:12 +03:00
|
|
|
durable=self.amqp_durable_queues,
|
2015-11-20 17:25:58 -05:00
|
|
|
exchange_auto_delete=self.amqp_auto_delete,
|
|
|
|
queue_auto_delete=self.amqp_auto_delete,
|
2015-05-13 17:51:12 +03:00
|
|
|
callback=callback,
|
|
|
|
rabbit_ha_queues=self.rabbit_ha_queues)
|
2015-04-30 17:46:42 +02:00
|
|
|
|
|
|
|
self.declare_consumer(consumer)
|
2013-07-23 16:28:15 +01:00
|
|
|
|
|
|
|
def declare_fanout_consumer(self, topic, callback):
|
|
|
|
"""Create a 'fanout' consumer."""
|
2015-04-30 17:46:42 +02:00
|
|
|
|
|
|
|
unique = uuid.uuid4().hex
|
|
|
|
exchange_name = '%s_fanout' % topic
|
|
|
|
queue_name = '%s_fanout_%s' % (topic, unique)
|
|
|
|
|
2015-05-13 17:51:12 +03:00
|
|
|
consumer = Consumer(exchange_name=exchange_name,
|
2015-04-30 17:46:42 +02:00
|
|
|
queue_name=queue_name,
|
|
|
|
routing_key=topic,
|
|
|
|
type='fanout',
|
|
|
|
durable=False,
|
2015-11-20 17:25:58 -05:00
|
|
|
exchange_auto_delete=True,
|
|
|
|
queue_auto_delete=False,
|
2015-04-30 17:46:42 +02:00
|
|
|
callback=callback,
|
2015-11-20 17:25:58 -05:00
|
|
|
rabbit_ha_queues=self.rabbit_ha_queues,
|
|
|
|
rabbit_queue_ttl=self.rabbit_transient_queues_ttl)
|
2015-04-30 17:46:42 +02:00
|
|
|
|
|
|
|
self.declare_consumer(consumer)
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2015-05-05 14:37:58 +02:00
|
|
|
def _ensure_publishing(self, method, exchange, msg, routing_key=None,
|
2019-05-21 14:39:55 +02:00
|
|
|
timeout=None, retry=None, transport_options=None):
|
2015-05-05 14:37:58 +02:00
|
|
|
"""Send to a publisher based on the publisher class."""
|
|
|
|
|
|
|
|
def _error_callback(exc):
|
|
|
|
log_info = {'topic': exchange.name, 'err_str': exc}
|
2019-04-11 10:47:24 +02:00
|
|
|
LOG.error("Failed to publish message to topic "
|
|
|
|
"'%(topic)s': %(err_str)s", log_info)
|
2015-05-05 14:37:58 +02:00
|
|
|
LOG.debug('Exception', exc_info=exc)
|
|
|
|
|
2019-05-21 14:39:55 +02:00
|
|
|
method = functools.partial(method, exchange, msg, routing_key,
|
|
|
|
timeout, transport_options)
|
2015-05-05 14:37:58 +02:00
|
|
|
|
|
|
|
with self._connection_lock:
|
|
|
|
self.ensure(method, retry=retry, error_callback=_error_callback)
|
|
|
|
|
2018-07-06 11:24:40 -04:00
|
|
|
def _get_connection_info(self, conn_error=False):
|
|
|
|
# Bug #1745166: set 'conn_error' true if this is being called when the
|
|
|
|
# connection is in a known error state. Otherwise attempting to access
|
|
|
|
# the connection's socket while it is in an error state will cause
|
|
|
|
# py-amqp to attempt reconnecting.
|
2018-08-20 12:31:16 -04:00
|
|
|
ci = self.connection.info()
|
|
|
|
info = dict([(k, ci.get(k)) for k in
|
|
|
|
['hostname', 'port', 'transport']])
|
2016-05-24 20:45:52 +03:00
|
|
|
client_port = None
|
2018-12-28 22:52:08 +08:00
|
|
|
if (not conn_error and self.channel and
|
|
|
|
hasattr(self.channel.connection, 'sock') and
|
|
|
|
self.channel.connection.sock):
|
2016-05-24 20:45:52 +03:00
|
|
|
client_port = self.channel.connection.sock.getsockname()[1]
|
|
|
|
info.update({'client_port': client_port,
|
|
|
|
'connection_id': self.connection_id})
|
|
|
|
return info
|
|
|
|
|
2019-05-21 14:39:55 +02:00
|
|
|
def _publish(self, exchange, msg, routing_key=None, timeout=None,
|
|
|
|
transport_options=None):
|
2015-05-05 14:37:58 +02:00
|
|
|
"""Publish a message."""
|
2016-04-29 05:55:55 +03:00
|
|
|
|
|
|
|
if not (exchange.passive or exchange.name in self._declared_exchanges):
|
|
|
|
exchange(self.channel).declare()
|
|
|
|
self._declared_exchanges.add(exchange.name)
|
2015-05-05 14:37:58 +02:00
|
|
|
|
2015-06-22 14:36:11 -04:00
|
|
|
log_info = {'msg': msg,
|
|
|
|
'who': exchange or 'default',
|
2019-05-21 14:39:55 +02:00
|
|
|
'key': routing_key,
|
|
|
|
'transport_options': str(transport_options)}
|
2015-06-22 14:36:11 -04:00
|
|
|
LOG.trace('Connection._publish: sending message %(msg)s to'
|
|
|
|
' %(who)s with routing key %(key)s', log_info)
|
2016-03-17 15:25:38 +01:00
|
|
|
# NOTE(sileht): no need to wait more, caller expects
|
|
|
|
# a answer before timeout is reached
|
|
|
|
with self._transport_socket_timeout(timeout):
|
2019-06-19 09:51:55 +02:00
|
|
|
self._producer.publish(
|
|
|
|
msg,
|
|
|
|
mandatory=transport_options.at_least_once if
|
|
|
|
transport_options else False,
|
|
|
|
exchange=exchange,
|
|
|
|
routing_key=routing_key,
|
|
|
|
expiration=timeout,
|
|
|
|
compression=self.kombu_compression)
|
2015-05-05 14:37:58 +02:00
|
|
|
|
|
|
|
def _publish_and_creates_default_queue(self, exchange, msg,
|
2019-05-21 14:39:55 +02:00
|
|
|
routing_key=None, timeout=None,
|
|
|
|
transport_options=None):
|
2015-05-05 14:37:58 +02:00
|
|
|
"""Publisher that declares a default queue
|
|
|
|
|
2015-05-13 09:00:54 +02:00
|
|
|
When the exchange is missing instead of silently creates an exchange
|
2015-05-05 14:37:58 +02:00
|
|
|
not binded to a queue, this publisher creates a default queue
|
|
|
|
named with the routing_key
|
|
|
|
|
|
|
|
This is mainly used to not miss notification in case of nobody consumes
|
2015-05-13 09:00:54 +02:00
|
|
|
them yet. If the future consumer bind the default queue it can retrieve
|
2015-05-05 14:37:58 +02:00
|
|
|
missing messages.
|
|
|
|
|
|
|
|
_set_current_channel is responsible to cleanup the cache.
|
|
|
|
"""
|
|
|
|
queue_indentifier = (exchange.name, routing_key)
|
|
|
|
# NOTE(sileht): We only do it once per reconnection
|
|
|
|
# the Connection._set_current_channel() is responsible to clear
|
|
|
|
# this cache
|
2016-04-29 05:55:55 +03:00
|
|
|
if queue_indentifier not in self._declared_queues:
|
2015-05-05 14:37:58 +02:00
|
|
|
queue = kombu.entity.Queue(
|
|
|
|
channel=self.channel,
|
|
|
|
exchange=exchange,
|
|
|
|
durable=exchange.durable,
|
|
|
|
auto_delete=exchange.auto_delete,
|
|
|
|
name=routing_key,
|
|
|
|
routing_key=routing_key,
|
2015-11-20 17:25:58 -05:00
|
|
|
queue_arguments=_get_queue_arguments(self.rabbit_ha_queues, 0))
|
2015-06-22 14:36:11 -04:00
|
|
|
log_info = {'key': routing_key, 'exchange': exchange}
|
|
|
|
LOG.trace(
|
|
|
|
'Connection._publish_and_creates_default_queue: '
|
|
|
|
'declare queue %(key)s on %(exchange)s exchange', log_info)
|
2015-05-05 14:37:58 +02:00
|
|
|
queue.declare()
|
2016-04-29 05:55:55 +03:00
|
|
|
self._declared_queues.add(queue_indentifier)
|
2015-05-05 14:37:58 +02:00
|
|
|
|
|
|
|
self._publish(exchange, msg, routing_key=routing_key, timeout=timeout)
|
|
|
|
|
2015-12-02 11:38:27 +01:00
|
|
|
def _publish_and_raises_on_missing_exchange(self, exchange, msg,
|
|
|
|
routing_key=None,
|
2019-05-21 14:39:55 +02:00
|
|
|
timeout=None,
|
|
|
|
transport_options=None):
|
2015-12-02 11:38:27 +01:00
|
|
|
"""Publisher that raises exception if exchange is missing."""
|
2015-05-05 14:37:58 +02:00
|
|
|
if not exchange.passive:
|
2015-07-02 13:56:29 +03:00
|
|
|
raise RuntimeError("_publish_and_retry_on_missing_exchange() must "
|
|
|
|
"be called with an passive exchange.")
|
2015-05-05 14:37:58 +02:00
|
|
|
|
2015-12-02 11:38:27 +01:00
|
|
|
try:
|
|
|
|
self._publish(exchange, msg, routing_key=routing_key,
|
2019-05-21 14:39:55 +02:00
|
|
|
timeout=timeout, transport_options=transport_options)
|
2015-12-02 11:38:27 +01:00
|
|
|
return
|
|
|
|
except self.connection.channel_errors as exc:
|
|
|
|
if exc.code == 404:
|
2015-05-05 14:37:58 +02:00
|
|
|
# NOTE(noelbk/sileht):
|
|
|
|
# If rabbit dies, the consumer can be disconnected before the
|
|
|
|
# publisher sends, and if the consumer hasn't declared the
|
|
|
|
# queue, the publisher's will send a message to an exchange
|
|
|
|
# that's not bound to a queue, and the message wll be lost.
|
|
|
|
# So we set passive=True to the publisher exchange and catch
|
|
|
|
# the 404 kombu ChannelError and retry until the exchange
|
|
|
|
# appears
|
2015-12-02 11:38:27 +01:00
|
|
|
raise rpc_amqp.AMQPDestinationNotFound(
|
|
|
|
"exchange %s doesn't exists" % exchange.name)
|
|
|
|
raise
|
2015-05-05 14:37:58 +02:00
|
|
|
|
2013-07-23 16:28:15 +01:00
|
|
|
def direct_send(self, msg_id, msg):
|
|
|
|
"""Send a 'direct' message."""
|
2018-08-27 12:18:58 +04:00
|
|
|
exchange = kombu.entity.Exchange(name='', # using default exchange
|
2015-05-05 14:37:58 +02:00
|
|
|
type='direct',
|
|
|
|
durable=False,
|
|
|
|
auto_delete=True,
|
|
|
|
passive=True)
|
2019-07-22 17:27:21 +02:00
|
|
|
options = oslo_messaging.TransportOptions(
|
|
|
|
at_least_once=self.direct_mandatory_flag)
|
2015-12-02 11:38:27 +01:00
|
|
|
self._ensure_publishing(self._publish_and_raises_on_missing_exchange,
|
2019-07-22 17:27:21 +02:00
|
|
|
exchange, msg, routing_key=msg_id,
|
|
|
|
transport_options=options)
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2019-05-21 14:39:55 +02:00
|
|
|
def topic_send(self, exchange_name, topic, msg, timeout=None, retry=None,
|
|
|
|
transport_options=None):
|
2013-07-23 16:28:15 +01:00
|
|
|
"""Send a 'topic' message."""
|
2015-05-05 14:37:58 +02:00
|
|
|
exchange = kombu.entity.Exchange(
|
|
|
|
name=exchange_name,
|
|
|
|
type='topic',
|
2015-05-13 17:51:12 +03:00
|
|
|
durable=self.amqp_durable_queues,
|
|
|
|
auto_delete=self.amqp_auto_delete)
|
2015-05-05 14:37:58 +02:00
|
|
|
|
|
|
|
self._ensure_publishing(self._publish, exchange, msg,
|
2016-01-05 19:21:44 +08:00
|
|
|
routing_key=topic, timeout=timeout,
|
2019-05-21 14:39:55 +02:00
|
|
|
retry=retry,
|
|
|
|
transport_options=transport_options)
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2014-02-21 11:50:45 +01:00
|
|
|
def fanout_send(self, topic, msg, retry=None):
|
2013-07-23 16:28:15 +01:00
|
|
|
"""Send a 'fanout' message."""
|
2015-05-05 14:37:58 +02:00
|
|
|
exchange = kombu.entity.Exchange(name='%s_fanout' % topic,
|
|
|
|
type='fanout',
|
|
|
|
durable=False,
|
|
|
|
auto_delete=True)
|
2015-04-30 16:13:14 +02:00
|
|
|
|
2015-05-05 14:37:58 +02:00
|
|
|
self._ensure_publishing(self._publish, exchange, msg, retry=retry)
|
2013-07-23 16:28:15 +01:00
|
|
|
|
2014-05-06 13:47:12 +02:00
|
|
|
def notify_send(self, exchange_name, topic, msg, retry=None, **kwargs):
|
2013-07-23 16:28:15 +01:00
|
|
|
"""Send a notify message on a topic."""
|
2015-05-05 14:37:58 +02:00
|
|
|
exchange = kombu.entity.Exchange(
|
|
|
|
name=exchange_name,
|
2015-04-30 16:13:14 +02:00
|
|
|
type='topic',
|
2015-05-13 17:51:12 +03:00
|
|
|
durable=self.amqp_durable_queues,
|
|
|
|
auto_delete=self.amqp_auto_delete)
|
2015-04-30 16:13:14 +02:00
|
|
|
|
2015-05-05 14:37:58 +02:00
|
|
|
self._ensure_publishing(self._publish_and_creates_default_queue,
|
|
|
|
exchange, msg, routing_key=topic, retry=retry)
|
2014-12-08 10:52:45 +01:00
|
|
|
|
2013-07-23 18:14:17 +01:00
|
|
|
|
2013-07-29 07:20:01 +01:00
|
|
|
class RabbitDriver(amqpdriver.AMQPDriverBase):
|
2015-05-16 15:13:31 -04:00
|
|
|
"""RabbitMQ Driver
|
|
|
|
|
|
|
|
The ``rabbit`` driver is the default driver used in OpenStack's
|
|
|
|
integration tests.
|
|
|
|
|
|
|
|
The driver is aliased as ``kombu`` to support upgrading existing
|
|
|
|
installations with older settings.
|
|
|
|
|
|
|
|
"""
|
2013-07-23 18:14:17 +01:00
|
|
|
|
2014-02-21 11:50:45 +01:00
|
|
|
def __init__(self, conf, url,
|
|
|
|
default_exchange=None,
|
2014-06-07 12:06:08 +08:00
|
|
|
allowed_remote_exmods=None):
|
2015-01-28 08:57:21 +01:00
|
|
|
opt_group = cfg.OptGroup(name='oslo_messaging_rabbit',
|
|
|
|
title='RabbitMQ driver options')
|
|
|
|
conf.register_group(opt_group)
|
|
|
|
conf.register_opts(rabbit_opts, group=opt_group)
|
|
|
|
conf.register_opts(rpc_amqp.amqp_opts, group=opt_group)
|
2015-04-23 17:08:24 +01:00
|
|
|
conf.register_opts(base.base_opts, group=opt_group)
|
2017-02-23 09:37:16 +01:00
|
|
|
conf = rpc_common.ConfigOptsProxy(conf, url, opt_group.name)
|
2015-01-28 08:57:21 +01:00
|
|
|
|
2015-12-02 11:38:27 +01:00
|
|
|
self.missing_destination_retry_timeout = (
|
2015-12-02 09:36:02 +01:00
|
|
|
conf.oslo_messaging_rabbit.kombu_missing_consumer_retry_timeout)
|
2015-12-02 11:38:27 +01:00
|
|
|
|
2016-01-19 22:59:38 -05:00
|
|
|
self.prefetch_size = (
|
|
|
|
conf.oslo_messaging_rabbit.rabbit_qos_prefetch_count)
|
|
|
|
|
2016-07-11 15:25:23 +03:00
|
|
|
# the pool configuration properties
|
|
|
|
max_size = conf.oslo_messaging_rabbit.rpc_conn_pool_size
|
|
|
|
min_size = conf.oslo_messaging_rabbit.conn_pool_min_size
|
|
|
|
ttl = conf.oslo_messaging_rabbit.conn_pool_ttl
|
|
|
|
|
2015-11-29 18:26:32 -05:00
|
|
|
connection_pool = pool.ConnectionPool(
|
2016-07-11 15:25:23 +03:00
|
|
|
conf, max_size, min_size, ttl,
|
2015-01-28 08:57:21 +01:00
|
|
|
url, Connection)
|
2013-07-23 18:14:17 +01:00
|
|
|
|
2015-05-22 12:26:55 +03:00
|
|
|
super(RabbitDriver, self).__init__(
|
|
|
|
conf, url,
|
|
|
|
connection_pool,
|
|
|
|
default_exchange,
|
2015-12-02 10:02:01 +01:00
|
|
|
allowed_remote_exmods
|
2015-05-22 12:26:55 +03:00
|
|
|
)
|
2014-03-03 07:35:29 -08:00
|
|
|
|
|
|
|
def require_features(self, requeue=True):
|
|
|
|
pass
|