summaryrefslogtreecommitdiff
path: root/oslo_messaging/rpc/client.py
blob: 8e997e9aeada6d6185f008838cb094e267df2828 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright 2013 Red Hat, Inc.
#
#    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.

import abc
import logging

from oslo_config import cfg

from oslo_messaging._drivers import base as driver_base
from oslo_messaging import _metrics as metrics
from oslo_messaging import _utils as utils
from oslo_messaging import exceptions
from oslo_messaging import serializer as msg_serializer
from oslo_messaging import transport as msg_transport

__all__ = [
    'ClientSendError',
    'RPCClient',
    'RPCVersionCapError',
    'RemoteError',
    'get_rpc_client',
]

LOG = logging.getLogger(__name__)

_client_opts = [
    cfg.IntOpt('rpc_response_timeout',
               default=60,
               help='Seconds to wait for a response from a call.'),
]


class RemoteError(exceptions.MessagingException):
    """Signifies that a remote endpoint method has raised an exception.

    Contains a string representation of the type of the original exception,
    the value of the original exception, and the traceback.  These are
    sent to the parent as a joined string so printing the exception
    contains all of the relevant info.
    """

    def __init__(self, exc_type=None, value=None, traceback=None):
        self.exc_type = exc_type
        self.value = value
        self.traceback = traceback
        msg = ("Remote error: %(exc_type)s %(value)s\n%(traceback)s." %
               dict(exc_type=self.exc_type, value=self.value,
                    traceback=self.traceback))
        super(RemoteError, self).__init__(msg)


class RPCVersionCapError(exceptions.MessagingException):

    def __init__(self, version, version_cap):
        self.version = version
        self.version_cap = version_cap
        msg = ("Requested message version, %(version)s is incompatible.  It "
               "needs to be equal in major version and less than or equal "
               "in minor version as the specified version cap "
               "%(version_cap)s." %
               dict(version=self.version, version_cap=self.version_cap))
        super(RPCVersionCapError, self).__init__(msg)


class ClientSendError(exceptions.MessagingException):
    """Raised if we failed to send a message to a target."""

    def __init__(self, target, ex):
        msg = 'Failed to send to target "%s": %s' % (target, ex)
        super(ClientSendError, self).__init__(msg)
        self.target = target
        self.ex = ex


class _BaseCallContext(object, metaclass=abc.ABCMeta):

    _marker = object()

    def __init__(self, transport, target, serializer,
                 timeout=None, version_cap=None, retry=None,
                 call_monitor_timeout=None, transport_options=None):
        self.conf = transport.conf

        self.transport = transport
        self.target = target
        self.serializer = serializer
        self.timeout = timeout
        self.call_monitor_timeout = call_monitor_timeout
        self.retry = retry
        self.version_cap = version_cap
        self.transport_options = transport_options

        super(_BaseCallContext, self).__init__()

    def _make_message(self, ctxt, method, args):
        msg = dict(method=method)

        msg['args'] = dict()
        for argname, arg in args.items():
            msg['args'][argname] = self.serializer.serialize_entity(ctxt, arg)

        if self.target.namespace is not None:
            msg['namespace'] = self.target.namespace
        if self.target.version is not None:
            msg['version'] = self.target.version

        return msg

    def _check_version_cap(self, version):
        if not utils.version_is_compatible(self.version_cap, version):
            raise RPCVersionCapError(version=version,
                                     version_cap=self.version_cap)

    def can_send_version(self, version=_marker):
        """Check to see if a version is compatible with the version cap."""
        version = self.target.version if version is self._marker else version
        return utils.version_is_compatible(self.version_cap, version)

    @classmethod
    def _check_version(cls, version):
        if version is not cls._marker:
            # quick sanity check to make sure parsable version numbers are used
            try:
                utils.version_is_compatible(version, version)
            except (IndexError, ValueError):
                raise exceptions.MessagingException(
                    "Version must contain a major and minor integer. Got %s"
                    % version)

    def cast(self, ctxt, method, **kwargs):
        """Invoke a method and return immediately. See RPCClient.cast()."""
        msg = self._make_message(ctxt, method, kwargs)
        msg_ctxt = self.serializer.serialize_context(ctxt)

        self._check_version_cap(msg.get('version'))

        with metrics.get_collector(self.conf, "rpc_client",
                                   target=self.target,
                                   method=method,
                                   call_type="cast") as metrics_collector:
            try:
                self.transport._send(self.target, msg_ctxt, msg,
                                     retry=self.retry,
                                     transport_options=self.transport_options)
            except driver_base.TransportDriverError as ex:
                self._metrics_api.rpc_client_exception_total(
                    self.target, method, "cast", ex.__class__.__name__)
                raise ClientSendError(self.target, ex)
            except Exception as ex:
                if self.conf.oslo_messaging_metrics.metrics_enabled:
                    metrics_collector.rpc_client_exception_total(
                        self.target, method, "cast", ex.__class__.__name__)
                raise

    def call(self, ctxt, method, **kwargs):
        """Invoke a method and wait for a reply. See RPCClient.call()."""
        if self.target.fanout:
            raise exceptions.InvalidTarget('A call cannot be used with fanout',
                                           self.target)

        msg = self._make_message(ctxt, method, kwargs)
        msg_ctxt = self.serializer.serialize_context(ctxt)

        timeout = self.timeout
        if self.timeout is None:
            timeout = self.conf.rpc_response_timeout

        cm_timeout = self.call_monitor_timeout

        self._check_version_cap(msg.get('version'))

        with metrics.get_collector(self.conf, "rpc_client",
                                   target=self.target, method=method,
                                   call_type="call") as metrics_collector:
            try:
                result = self.transport._send(
                    self.target, msg_ctxt, msg, wait_for_reply=True,
                    timeout=timeout, call_monitor_timeout=cm_timeout,
                    retry=self.retry, transport_options=self.transport_options)
            except driver_base.TransportDriverError as ex:
                self._metrics_api.rpc_client_exception_total(
                    self.target, method, "call", ex.__class__.__name__)
                raise ClientSendError(self.target, ex)
            except Exception as ex:
                if self.conf.oslo_messaging_metrics.metrics_enabled:
                    metrics_collector.rpc_client_exception_total(
                        self.target, method, "call", ex.__class__.__name__)
                raise
            return self.serializer.deserialize_entity(ctxt, result)

    @abc.abstractmethod
    def prepare(self, exchange=_marker, topic=_marker, namespace=_marker,
                version=_marker, server=_marker, fanout=_marker,
                timeout=_marker, version_cap=_marker, retry=_marker,
                call_monitor_timeout=_marker):
        """Prepare a method invocation context. See RPCClient.prepare()."""


class _CallContext(_BaseCallContext):
    _marker = _BaseCallContext._marker

    @classmethod
    def _prepare(cls, call_context,
                 exchange=_marker, topic=_marker, namespace=_marker,
                 version=_marker, server=_marker, fanout=_marker,
                 timeout=_marker, version_cap=_marker, retry=_marker,
                 call_monitor_timeout=_marker, transport_options=_marker):
        cls._check_version(version)
        kwargs = dict(
            exchange=exchange,
            topic=topic,
            namespace=namespace,
            version=version,
            server=server,
            fanout=fanout)
        kwargs = dict([(k, v) for k, v in kwargs.items()
                       if v is not cls._marker])
        target = call_context.target(**kwargs)

        if timeout is cls._marker:
            timeout = call_context.timeout
        if version_cap is cls._marker:
            version_cap = call_context.version_cap
        if retry is cls._marker:
            retry = call_context.retry
        if call_monitor_timeout is cls._marker:
            call_monitor_timeout = call_context.call_monitor_timeout
        if transport_options is cls._marker:
            transport_options = call_context.transport_options

        return _CallContext(call_context.transport, target,
                            call_context.serializer,
                            timeout, version_cap, retry,
                            call_monitor_timeout, transport_options)

    def prepare(self, exchange=_marker, topic=_marker, namespace=_marker,
                version=_marker, server=_marker, fanout=_marker,
                timeout=_marker, version_cap=_marker, retry=_marker,
                call_monitor_timeout=_marker):
        return _CallContext._prepare(self,
                                     exchange, topic, namespace,
                                     version, server, fanout,
                                     timeout, version_cap, retry,
                                     call_monitor_timeout)


class RPCClient(_BaseCallContext):
    """A class for invoking methods on remote RPC servers.

    The RPCClient class is responsible for sending method invocations to and
    receiving return values from remote RPC servers via a messaging transport.

    The class should always be instantiated by using the get_rpc_client
    function and not constructing the class directly.

    Two RPC patterns are supported: RPC calls and RPC casts.

    An RPC cast is used when an RPC method does *not* return a value to
    the caller. An RPC call is used when a return value is expected from the
    method.  For further information see the cast() and call() methods.

    The default target used for all subsequent calls and casts is supplied to
    the RPCClient constructor.  The client uses the target to control how the
    RPC request is delivered to a server.  If only the target's topic (and
    optionally exchange) are set, then the RPC can be serviced by any server
    that is listening to that topic (and exchange).  If multiple servers are
    listening on that topic/exchange, then one server is picked using a
    best-effort round-robin algorithm.  Alternatively, the client can set the
    Target's ``server`` attribute to the name of a specific server to send the
    RPC request to one particular server.  In the case of RPC cast, the RPC
    request can be broadcast to all servers listening to the Target's
    topic/exchange by setting the Target's ``fanout`` property to ``True``.

    While the default target is set on construction, target attributes can be
    overridden for individual method invocations using the prepare() method.

    A method invocation consists of a request context dictionary, a method name
    and a dictionary of arguments.

    This class is intended to be used by wrapping it in another class which
    provides methods on the subclass to perform the remote invocation using
    call() or cast()::

        class TestClient(object):

            def __init__(self, transport):
                target = messaging.Target(topic='test', version='2.0')
                self._client = messaging.get_rpc_client(transport, target)

            def test(self, ctxt, arg):
                return self._client.call(ctxt, 'test', arg=arg)

    An example of using the prepare() method to override some attributes of the
    default target::

        def test(self, ctxt, arg):
            cctxt = self._client.prepare(version='2.5')
            return cctxt.call(ctxt, 'test', arg=arg)

    RPCClient have a number of other properties - for example, timeout and
    version_cap - which may make sense to override for some method invocations,
    so they too can be passed to prepare()::

        def test(self, ctxt, arg):
            cctxt = self._client.prepare(timeout=10)
            return cctxt.call(ctxt, 'test', arg=arg)

    However, this class can be used directly without wrapping it another class.
    For example::

        transport = messaging.get_rpc_transport(cfg.CONF)
        target = messaging.Target(topic='test', version='2.0')
        client = messaging.get_rpc_client(transport, target)
        client.call(ctxt, 'test', arg=arg)

    but this is probably only useful in limited circumstances as a wrapper
    class will usually help to make the code much more obvious.

    If the connection to the messaging service is not active when an RPC
    request is made the client will block waiting for the connection to
    complete.  If the connection fails to complete, the client will try to
    re-establish that connection. By default this will continue indefinitely
    until the connection completes. However, the retry parameter can be used to
    have the RPC request fail with a MessageDeliveryFailure after the given
    number of retries. For example::

        client = messaging.get_rpc_client(transport, target, retry=None)
        client.call(ctxt, 'sync')
        try:
            client.prepare(retry=0).cast(ctxt, 'ping')
        except messaging.MessageDeliveryFailure:
            LOG.error("Failed to send ping message")
    """

    _marker = _BaseCallContext._marker

    def __init__(self, transport, target,
                 timeout=None, version_cap=None, serializer=None, retry=None,
                 call_monitor_timeout=None, transport_options=None,
                 _manual_load=True):
        """Construct an RPC client.

        This should not be called directly, use the get_rpc_client function
        to instantiate this class.

        :param transport: a messaging transport handle
        :type transport: Transport
        :param target: the default target for invocations
        :type target: Target
        :param timeout: an optional default timeout (in seconds) for call()s
        :type timeout: int or float
        :param version_cap: raise a RPCVersionCapError version exceeds this cap
        :type version_cap: str
        :param serializer: an optional entity serializer
        :type serializer: Serializer
        :param retry: an optional default connection retries configuration:
                      None or -1 means to retry forever.
                      0 means no retry is attempted.
                      N means attempt at most N retries.
        :type retry: int
        :param call_monitor_timeout: an optional timeout (in seconds) for
                                     active call heartbeating. If specified,
                                     requires the server to heartbeat
                                     long-running calls at this interval
                                     (less than the overall timeout
                                     parameter).
        :type call_monitor_timeout: int
        :param transport_options: Transport options passed to client.
        :type transport_options: TransportOptions
        :param _manual_load: Internal use only to check if class was
                             manually instantiated or not.
        :type _manual_load: bool
        """
        if _manual_load:
            LOG.warning("Using RPCClient manually to instantiate client. "
                        "Please use get_rpc_client to obtain an RPC client "
                        "instance.")

        if serializer is None:
            serializer = msg_serializer.NoOpSerializer()

        if not isinstance(transport, msg_transport.RPCTransport):
            LOG.warning("Using notification transport for RPC. Please use "
                        "get_rpc_transport to obtain an RPC transport "
                        "instance.")

        super(RPCClient, self).__init__(
            transport, target, serializer, timeout, version_cap, retry,
            call_monitor_timeout, transport_options
        )

        self.conf.register_opts(_client_opts)

    def prepare(self, exchange=_marker, topic=_marker, namespace=_marker,
                version=_marker, server=_marker, fanout=_marker,
                timeout=_marker, version_cap=_marker, retry=_marker,
                call_monitor_timeout=_marker, transport_options=_marker):
        """Prepare a method invocation context.

        Use this method to override client properties for an individual method
        invocation. For example::

            def test(self, ctxt, arg):
                cctxt = self.prepare(version='2.5')
                return cctxt.call(ctxt, 'test', arg=arg)

        :param exchange: see Target.exchange
        :type exchange: str
        :param topic: see Target.topic
        :type topic: str
        :param namespace: see Target.namespace
        :type namespace: str
        :param version: requirement the server must support, see Target.version
        :type version: str
        :param server: send to a specific server, see Target.server
        :type server: str
        :param fanout: send to all servers on topic, see Target.fanout
        :type fanout: bool
        :param timeout: an optional default timeout (in seconds) for call()s
        :type timeout: int or float
        :param version_cap: raise a RPCVersionCapError version exceeds this cap
        :type version_cap: str
        :param retry: an optional connection retries configuration:
                      None or -1 means to retry forever.
                      0 means no retry is attempted.
                      N means attempt at most N retries.
        :type retry: int
        :param transport_options: additional parameters to configure the driver
                                  for example to send parameters as "mandatory"
                                  flag in RabbitMQ
        :type transport_options: dictionary
        :param call_monitor_timeout: an optional timeout (in seconds) for
                                     active call heartbeating. If specified,
                                     requires the server to heartbeat
                                     long-running calls at this interval
                                     (less than the overall timeout
                                     parameter).
        :type call_monitor_timeout: int
        """
        return _CallContext._prepare(self,
                                     exchange, topic, namespace,
                                     version, server, fanout,
                                     timeout, version_cap, retry,
                                     call_monitor_timeout, transport_options)

    def cast(self, ctxt, method, **kwargs):
        """Invoke a method without blocking for a return value.

        The cast() method is used to invoke an RPC method that does not return
        a value.  cast() RPC requests may be broadcast to all Servers listening
        on a given topic by setting the fanout Target property to ``True``.

        The cast() operation is best-effort: cast() will block the
        calling thread until the RPC request method is accepted by the
        messaging transport, but cast() does *not* verify that the RPC method
        has been invoked by the server. cast() does guarantee that the
        method will be not executed twice on a destination (e.g. 'at-most-once'
        execution).

        There are no ordering guarantees across successive casts, even
        among casts to the same destination. Therefore methods may be executed
        in an order different from the order in which they are cast.

        Method arguments must either be primitive types or types supported by
        the client's serializer (if any).

        Similarly, the request context must be a dict unless the client's
        serializer supports serializing another type.

        :param ctxt: a request context dict
        :type ctxt: dict
        :param method: the method name
        :type method: str
        :param kwargs: a dict of method arguments
        :type kwargs: dict
        :raises: MessageDeliveryFailure if the messaging transport fails to
                 accept the request.

        """
        self.prepare().cast(ctxt, method, **kwargs)

    def call(self, ctxt, method, **kwargs):
        """Invoke a method and wait for a reply.

        The call() method is used to invoke RPC methods that return a
        value. Since only a single return value is permitted it is not possible
        to call() to a fanout target.

        call() will block the calling thread until the messaging transport
        provides the return value, a timeout occurs, or a non-recoverable error
        occurs.

        call() guarantees that the RPC request is done 'at-most-once' which
        ensures that the call will never be duplicated.  However if the call
        should fail or time out before the return value arrives then there are
        no guarantees whether or not the method was invoked.

        Since call() blocks until completion of the RPC method, call()s from
        the same thread are guaranteed to be processed in-order.

        Method arguments must either be primitive types or types supported by
        the client's serializer (if any). Similarly, the request context must
        be a dict unless the client's serializer supports serializing another
        type.

        The semantics of how any errors raised by the remote RPC endpoint
        method are handled are quite subtle.

        Firstly, if the remote exception is contained in one of the modules
        listed in the allow_remote_exmods messaging.get_rpc_transport()
        parameter, then it this exception will be re-raised by call(). However,
        such locally re-raised remote exceptions are distinguishable from the
        same exception type raised locally because re-raised remote exceptions
        are modified such that their class name ends with the '_Remote' suffix
        so you may do::

            if ex.__class__.__name__.endswith('_Remote'):
                # Some special case for locally re-raised remote exceptions

        Secondly, if a remote exception is not from a module listed in the
        allowed_remote_exmods list, then a messaging.RemoteError exception is
        raised with all details of the remote exception.

        :param ctxt: a request context dict
        :type ctxt: dict
        :param method: the method name
        :type method: str
        :param kwargs: a dict of method arguments
        :type kwargs: dict
        :raises: MessagingTimeout, RemoteError, MessageDeliveryFailure
        """
        return self.prepare().call(ctxt, method, **kwargs)

    def can_send_version(self, version=_marker):
        """Check to see if a version is compatible with the version cap."""
        return self.prepare(version=version).can_send_version()


def get_rpc_client(transport, target, **kwargs):
    """Construct an RPC client.

    :param transport: the messaging transport
    :type transport: Transport
    :param target: the exchange, topic and server to listen on
    :type target: Target
    :param **kwargs: The kwargs will be passed down to the
                     RPCClient constructor
    """
    return RPCClient(transport, target, _manual_load=False, **kwargs)