| 1 |
# Copyright (c) 2012 OpenStack Foundation. |
| 2 |
# Copyright (c) 2014 Red Hat, Inc. |
| 3 |
# All Rights Reserved. |
| 4 |
# |
| 5 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 6 |
# not use this file except in compliance with the License. You may obtain |
| 7 |
# a copy of the License at |
| 8 |
# |
| 9 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 |
# |
| 11 |
# Unless required by applicable law or agreed to in writing, software |
| 12 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 13 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 14 |
# License for the specific language governing permissions and limitations |
| 15 |
# under the License. |
| 16 |
|
| 17 |
import collections |
| 18 |
import random |
| 19 |
import time |
| 20 |
|
| 21 |
from oslo_config import cfg |
| 22 |
from oslo_log import log as logging |
| 23 |
import oslo_messaging |
| 24 |
from oslo_messaging import exceptions as oslomsg_exc |
| 25 |
from oslo_messaging import serializer as om_serializer |
| 26 |
from oslo_service import service as os_service |
| 27 |
from oslo_utils import excutils |
| 28 |
from osprofiler import profiler |
| 29 |
|
| 30 |
from neutron_lib._i18n import _ |
| 31 |
from neutron_lib import context |
| 32 |
from neutron_lib import exceptions |
| 33 |
from neutron_lib.utils import runtime |
| 34 |
|
| 35 |
|
| 36 |
LOG = logging.getLogger(__name__) |
| 37 |
TRANSPORT = None |
| 38 |
NOTIFICATION_TRANSPORT = None |
| 39 |
|
| 40 |
_DFT_EXMODS = runtime.list_package_modules(exceptions.__name__) |
| 41 |
|
| 42 |
|
| 43 |
def init(conf, rpc_ext_mods=None): |
| 44 |
"""Initialize the global RPC objects. |
| 45 |
|
| 46 |
:param conf: The oslo conf to use for initialization. |
| 47 |
:param rpc_ext_mods: Exception modules to expose via RPC. |
| 48 |
:returns: None. |
| 49 |
""" |
| 50 |
global TRANSPORT, NOTIFICATION_TRANSPORT |
| 51 |
|
| 52 |
if rpc_ext_mods is None: |
| 53 |
rpc_ext_mods = _DFT_EXMODS |
| 54 |
else: |
| 55 |
rpc_ext_mods = list(set(rpc_ext_mods + _DFT_EXMODS)) |
| 56 |
|
| 57 |
TRANSPORT = oslo_messaging.get_rpc_transport( |
| 58 |
conf, allowed_remote_exmods=rpc_ext_mods) |
| 59 |
NOTIFICATION_TRANSPORT = oslo_messaging.get_notification_transport( |
| 60 |
conf, allowed_remote_exmods=rpc_ext_mods) |
| 61 |
|
| 62 |
|
| 63 |
def cleanup(): |
| 64 |
"""Deactivate and cleanup the global RPC objects. |
| 65 |
|
| 66 |
:returns: None. |
| 67 |
""" |
| 68 |
global TRANSPORT, NOTIFICATION_TRANSPORT |
| 69 |
if TRANSPORT is None: |
| 70 |
raise AssertionError(_("'TRANSPORT' must not be None")) |
| 71 |
if NOTIFICATION_TRANSPORT is None: |
| 72 |
raise AssertionError( |
| 73 |
_("'NOTIFICATION_TRANSPORT' must not be None")) |
| 74 |
TRANSPORT.cleanup() |
| 75 |
NOTIFICATION_TRANSPORT.cleanup() |
| 76 |
_BackingOffContextWrapper.reset_timeouts() |
| 77 |
TRANSPORT = NOTIFICATION_TRANSPORT = None |
| 78 |
|
| 79 |
|
| 80 |
def _get_default_method_timeout(): |
| 81 |
return TRANSPORT.conf.rpc_response_timeout |
| 82 |
|
| 83 |
|
| 84 |
def _get_default_method_timeouts(): |
| 85 |
return collections.defaultdict(_get_default_method_timeout) |
| 86 |
|
| 87 |
|
| 88 |
def _get_rpc_response_max_timeout(): |
| 89 |
return TRANSPORT.conf.rpc_response_max_timeout |
| 90 |
|
| 91 |
|
| 92 |
class _ContextWrapper: |
| 93 |
def __init__(self, original_context): |
| 94 |
self._original_context = original_context |
| 95 |
|
| 96 |
def __getattr__(self, name): |
| 97 |
return getattr(self._original_context, name) |
| 98 |
|
| 99 |
def cast(self, ctxt, method, **kwargs): |
| 100 |
try: |
| 101 |
self._original_context.cast(ctxt, method, **kwargs) |
| 102 |
except oslomsg_exc.MessageDeliveryFailure as e: |
| 103 |
LOG.debug("Ignored exception during cast: %s", str(e)) |
| 104 |
|
| 105 |
|
| 106 |
class _BackingOffContextWrapper(_ContextWrapper): |
| 107 |
"""Wraps oslo messaging contexts to set the timeout for calls. |
| 108 |
|
| 109 |
This intercepts RPC calls and sets the timeout value to the globally |
| 110 |
adapting value for each method. An oslo messaging timeout results in |
| 111 |
a doubling of the timeout value for the method on which it timed out. |
| 112 |
There currently is no logic to reduce the timeout since busy Neutron |
| 113 |
servers are more frequently the cause of timeouts rather than lost |
| 114 |
messages. |
| 115 |
""" |
| 116 |
_METHOD_TIMEOUTS = _get_default_method_timeouts() |
| 117 |
_max_timeout = None |
| 118 |
|
| 119 |
@classmethod |
| 120 |
def reset_timeouts(cls): |
| 121 |
# restore the original default timeout factory |
| 122 |
cls._METHOD_TIMEOUTS = _get_default_method_timeouts() |
| 123 |
cls._max_timeout = None |
| 124 |
|
| 125 |
@classmethod |
| 126 |
def get_max_timeout(cls): |
| 127 |
return cls._max_timeout or _get_rpc_response_max_timeout() |
| 128 |
|
| 129 |
@classmethod |
| 130 |
def set_max_timeout(cls, max_timeout): |
| 131 |
if max_timeout < cls.get_max_timeout(): |
| 132 |
cls._METHOD_TIMEOUTS.default_factory = lambda: max_timeout |
| 133 |
for k, v in cls._METHOD_TIMEOUTS.items(): |
| 134 |
if v > max_timeout: |
| 135 |
cls._METHOD_TIMEOUTS[k] = max_timeout |
| 136 |
cls._max_timeout = max_timeout |
| 137 |
|
| 138 |
def call(self, ctxt, method, **kwargs): |
| 139 |
# two methods with the same name in different namespaces should |
| 140 |
# be tracked independently |
| 141 |
if self._original_context.target.namespace: |
| 142 |
scoped_method = ( |
| 143 |
f'{self._original_context.target.namespace}.{method}') |
| 144 |
else: |
| 145 |
scoped_method = method |
| 146 |
# set the timeout from the global method timeout tracker for this |
| 147 |
# method |
| 148 |
self._original_context.timeout = self._METHOD_TIMEOUTS[scoped_method] |
| 149 |
try: |
| 150 |
return self._original_context.call(ctxt, method, **kwargs) |
| 151 |
except oslo_messaging.MessagingTimeout: |
| 152 |
with excutils.save_and_reraise_exception(): |
| 153 |
wait = random.uniform( |
| 154 |
0, |
| 155 |
min(self._METHOD_TIMEOUTS[scoped_method], |
| 156 |
TRANSPORT.conf.rpc_response_timeout) |
| 157 |
) |
| 158 |
LOG.error("Timeout in RPC method %(method)s. Waiting for " |
| 159 |
"%(wait)s seconds before next attempt. If the " |
| 160 |
"server is not down, consider increasing the " |
| 161 |
"rpc_response_timeout option as Neutron " |
| 162 |
"server(s) may be overloaded and unable to " |
| 163 |
"respond quickly enough.", |
| 164 |
{'wait': int(round(wait)), 'method': scoped_method}) |
| 165 |
new_timeout = min( |
| 166 |
self._original_context.timeout * 2, self.get_max_timeout()) |
| 167 |
if new_timeout > self._METHOD_TIMEOUTS[scoped_method]: |
| 168 |
LOG.warning("Increasing timeout for %(method)s calls " |
| 169 |
"to %(new)s seconds. Restart the agent to " |
| 170 |
"restore it to the default value.", |
| 171 |
{'method': scoped_method, 'new': new_timeout}) |
| 172 |
self._METHOD_TIMEOUTS[scoped_method] = new_timeout |
| 173 |
time.sleep(wait) |
| 174 |
|
| 175 |
|
| 176 |
class BackingOffClient(oslo_messaging.RPCClient): |
| 177 |
"""An oslo messaging RPC Client that implements a timeout backoff. |
| 178 |
|
| 179 |
This has all of the same interfaces as oslo_messaging.RPCClient but |
| 180 |
if the timeout parameter is not specified, the _BackingOffContextWrapper |
| 181 |
returned will track when call timeout exceptions occur and exponentially |
| 182 |
increase the timeout for the given call method. |
| 183 |
""" |
| 184 |
|
| 185 |
def prepare(self, *args, **kwargs): |
| 186 |
ctx = super().prepare(*args, **kwargs) |
| 187 |
# don't back off contexts that explicitly set a timeout |
| 188 |
if 'timeout' in kwargs: |
| 189 |
return _ContextWrapper(ctx) |
| 190 |
return _BackingOffContextWrapper(ctx) |
| 191 |
|
| 192 |
@staticmethod |
| 193 |
def set_max_timeout(max_timeout): |
| 194 |
'''Set RPC timeout ceiling for all backing-off RPC clients.''' |
| 195 |
_BackingOffContextWrapper.set_max_timeout(max_timeout) |
| 196 |
|
| 197 |
|
| 198 |
def get_client(target, version_cap=None, serializer=None): |
| 199 |
"""Get an RPC client for the said target. |
| 200 |
|
| 201 |
The init() function must be called prior to calling this. |
| 202 |
:param target: The RPC target for the client. |
| 203 |
:param version_cap: The optional version cap for the RPC client. |
| 204 |
:param serializer: The optional serializer to use for the RPC client. |
| 205 |
:returns: A new RPC client. |
| 206 |
""" |
| 207 |
if TRANSPORT is None: |
| 208 |
raise AssertionError(_("'TRANSPORT' must not be None")) |
| 209 |
serializer = RequestContextSerializer(serializer) |
| 210 |
return oslo_messaging.get_rpc_client( |
| 211 |
TRANSPORT, target, version_cap=version_cap, |
| 212 |
serializer=serializer, client_cls=BackingOffClient) |
| 213 |
|
| 214 |
|
| 215 |
def get_server(target, endpoints, serializer=None): |
| 216 |
"""Get a new RPC server reference. |
| 217 |
|
| 218 |
:param target: The target for the new RPC server. |
| 219 |
:param endpoints: The endpoints for the RPC server. |
| 220 |
:param serializer: The optional serialize to use for the RPC server. |
| 221 |
:returns: A new RPC server reference. |
| 222 |
""" |
| 223 |
if TRANSPORT is None: |
| 224 |
raise AssertionError(_("'TRANSPORT' must not be None")) |
| 225 |
serializer = RequestContextSerializer(serializer) |
| 226 |
return oslo_messaging.get_rpc_server(TRANSPORT, target, endpoints, |
| 227 |
serializer=serializer) |
| 228 |
|
| 229 |
|
| 230 |
def get_notifier(service=None, host=None, publisher_id=None): |
| 231 |
"""Get a new notifier reference. |
| 232 |
|
| 233 |
:param service: The optional service for the notifier. If not given, |
| 234 |
`None` is used as the service name (deprecated since 2025.1). |
| 235 |
:param host: The optional host for the notifier. If not given, the host |
| 236 |
will be taken from the global CONF. |
| 237 |
:param publisher_id: The optional publisher ID for the notifier. Overrides |
| 238 |
`service` and `host` arguments. |
| 239 |
:returns: A new RPC notifier reference. |
| 240 |
""" |
| 241 |
if NOTIFICATION_TRANSPORT is None: |
| 242 |
raise AssertionError(_("'NOTIFICATION_TRANSPORT' must not be None")) |
| 243 |
if not publisher_id: |
| 244 |
if service is None: |
| 245 |
LOG.warning("The 'service' argument to get_notifier is set to " |
| 246 |
"None. This is deprecated since 2025.1 release and " |
| 247 |
"will be removed in one of the future releases. " |
| 248 |
"Please always pass the 'service' argument.") |
| 249 |
publisher_id = f"{service}.{host or cfg.CONF.host}" |
| 250 |
serializer = RequestContextSerializer() |
| 251 |
return oslo_messaging.Notifier(NOTIFICATION_TRANSPORT, |
| 252 |
serializer=serializer, |
| 253 |
publisher_id=publisher_id) |
| 254 |
|
| 255 |
|
| 256 |
class RequestContextSerializer(om_serializer.Serializer): |
| 257 |
"""Convert RPC common context into Neutron Context.""" |
| 258 |
|
| 259 |
def __init__(self, base=None): |
| 260 |
super().__init__() |
| 261 |
self._base = base |
| 262 |
|
| 263 |
def serialize_entity(self, ctxt, entity): |
| 264 |
if not self._base: |
| 265 |
return entity |
| 266 |
return self._base.serialize_entity(ctxt, entity) |
| 267 |
|
| 268 |
def deserialize_entity(self, ctxt, entity): |
| 269 |
if not self._base: |
| 270 |
return entity |
| 271 |
return self._base.deserialize_entity(ctxt, entity) |
| 272 |
|
| 273 |
def serialize_context(self, ctxt): |
| 274 |
_context = ctxt.to_dict() |
| 275 |
prof = profiler.get() |
| 276 |
if prof: |
| 277 |
trace_info = { |
| 278 |
"hmac_key": prof.hmac_key, |
| 279 |
"base_id": prof.get_base_id(), |
| 280 |
"parent_id": prof.get_id() |
| 281 |
} |
| 282 |
_context['trace_info'] = trace_info |
| 283 |
return _context |
| 284 |
|
| 285 |
def deserialize_context(self, ctxt): |
| 286 |
rpc_ctxt_dict = ctxt.copy() |
| 287 |
trace_info = rpc_ctxt_dict.pop("trace_info", None) |
| 288 |
if trace_info: |
| 289 |
profiler.init(**trace_info) |
| 290 |
return context.Context.from_dict(rpc_ctxt_dict) |
| 291 |
|
| 292 |
|
| 293 |
@profiler.trace_cls("rpc") |
| 294 |
class Service(os_service.Service): |
| 295 |
"""Service object for binaries running on hosts. |
| 296 |
|
| 297 |
A service enables rpc by listening to queues based on topic and host. |
| 298 |
""" |
| 299 |
|
| 300 |
def __init__(self, host, topic, manager=None, serializer=None): |
| 301 |
super().__init__() |
| 302 |
self.host = host |
| 303 |
self.topic = topic |
| 304 |
self.serializer = serializer |
| 305 |
if manager is None: |
| 306 |
self.manager = self |
| 307 |
else: |
| 308 |
self.manager = manager |
| 309 |
|
| 310 |
def start(self): |
| 311 |
super().start() |
| 312 |
|
| 313 |
self.conn = Connection() |
| 314 |
LOG.debug("Creating Consumer connection for Service %s", |
| 315 |
self.topic) |
| 316 |
|
| 317 |
endpoints = [self.manager] |
| 318 |
|
| 319 |
self.conn.create_consumer(self.topic, endpoints) |
| 320 |
|
| 321 |
# Hook to allow the manager to do other initializations after |
| 322 |
# the rpc connection is created. |
| 323 |
if callable(getattr(self.manager, 'initialize_service_hook', None)): |
| 324 |
self.manager.initialize_service_hook(self) |
| 325 |
|
| 326 |
# Consume from all consumers in threads |
| 327 |
self.conn.consume_in_threads() |
| 328 |
|
| 329 |
def stop(self): |
| 330 |
# Try to shut the connection down, but if we get any sort of |
| 331 |
# errors, go ahead and ignore them.. as we're shutting down anyway |
| 332 |
try: |
| 333 |
self.conn.close() |
| 334 |
except Exception as e: |
| 335 |
LOG.debug("Ignored exception during stop: %s", str(e)) |
| 336 |
pass |
| 337 |
super().stop() |
| 338 |
|
| 339 |
|
| 340 |
class Connection: |
| 341 |
"""A utility class that manages a collection of RPC servers.""" |
| 342 |
|
| 343 |
def __init__(self): |
| 344 |
super().__init__() |
| 345 |
self.servers = [] |
| 346 |
|
| 347 |
def create_consumer(self, topic, endpoints, fanout=False): |
| 348 |
target = oslo_messaging.Target( |
| 349 |
topic=topic, server=cfg.CONF.host, fanout=fanout) |
| 350 |
server = get_server(target, endpoints) |
| 351 |
self.servers.append(server) |
| 352 |
|
| 353 |
def consume_in_threads(self): |
| 354 |
for server in self.servers: |
| 355 |
server.start() |
| 356 |
return self.servers |
| 357 |
|
| 358 |
def close(self): |
| 359 |
for server in self.servers: |
| 360 |
server.stop() |
| 361 |
for server in self.servers: |
| 362 |
server.wait() |