예제 #1
0
    def test_notifier(self, mock_utcnow):
        drivers = []
        if self.v1:
            drivers.append('messaging')
        if self.v2:
            drivers.append('messagingv2')

        self.config(notification_driver=drivers,
                    notification_topics=self.topics)

        transport = _FakeTransport(self.conf)

        if hasattr(self, 'ctor_pub_id'):
            notifier = messaging.Notifier(transport,
                                          publisher_id=self.ctor_pub_id)
        else:
            notifier = messaging.Notifier(transport)

        if hasattr(self, 'prep_pub_id'):
            notifier = notifier.prepare(publisher_id=self.prep_pub_id)

        self.mox.StubOutWithMock(transport, '_send_notification')

        message_id = uuid.uuid4()
        self.mox.StubOutWithMock(uuid, 'uuid4')
        uuid.uuid4().AndReturn(message_id)

        mock_utcnow.return_value = datetime.datetime.utcnow()

        message = {
            'message_id': str(message_id),
            'publisher_id': self.expected_pub_id,
            'event_type': 'test.notify',
            'priority': self.priority.upper(),
            'payload': self.payload,
            'timestamp': str(timeutils.utcnow()),
        }

        sends = []
        if self.v1:
            sends.append(dict(version=1.0))
        if self.v2:
            sends.append(dict(version=2.0))

        for send_kwargs in sends:
            for topic in self.topics:
                target = messaging.Target(topic='%s.%s' %
                                          (topic, self.priority))
                transport._send_notification(target, self.ctxt, message,
                                             **send_kwargs).InAnyOrder()

        self.mox.ReplayAll()

        method = getattr(notifier, self.priority)
        method(self.ctxt, 'test.notify', self.payload)
예제 #2
0
def init(conf):
    global TRANSPORT, NOTIFIER
    exmods = get_allowed_exmods()
    TRANSPORT = messaging.get_transport(conf,
                                        allowed_remote_exmods=exmods,
                                        aliases=TRANSPORT_ALIASES)
    NOTIFIER = messaging.Notifier(TRANSPORT)
예제 #3
0
    def setUp(self):
        super(TestRoutingNotifier, self).setUp()
        self.config(notification_driver=['routing'])

        transport = _FakeTransport(self.conf)
        self.notifier = messaging.Notifier(transport)
        self.router = self.notifier._driver_mgr['routing'].obj
예제 #4
0
    def test_notifier(self, mock_utcnow):
        self.config(notification_driver=['log'])

        transport = _FakeTransport(self.conf)

        notifier = messaging.Notifier(transport, 'test.localhost')

        message_id = uuid.uuid4()
        self.mox.StubOutWithMock(uuid, 'uuid4')
        uuid.uuid4().AndReturn(message_id)

        mock_utcnow.return_value = datetime.datetime.utcnow()

        message = {
            'message_id': str(message_id),
            'publisher_id': 'test.localhost',
            'event_type': 'test.notify',
            'priority': 'INFO',
            'payload': 'bar',
            'timestamp': str(timeutils.utcnow()),
        }

        logger = self.mox.CreateMockAnything()

        self.mox.StubOutWithMock(logging, 'getLogger')
        logging.getLogger('oslo.messaging.notification.test.notify').\
            AndReturn(logger)

        logger.info(jsonutils.dumps(message))

        self.mox.ReplayAll()

        notifier.info({}, 'test.notify', 'bar')
예제 #5
0
파일: notifier.py 프로젝트: afliu/glance
    def __init__(self, strategy=None):

        if CONF.notifier_strategy != 'default':
            msg = _("notifier_strategy was deprecated in "
                    "favor of `notification_driver`")
            warnings.warn(msg, DeprecationWarning)

        # NOTE(flaper87): Use this to keep backwards
        # compatibility. We'll try to get an oslo.messaging
        # driver from the specified strategy.
        _strategy = strategy or CONF.notifier_strategy
        _driver = _STRATEGY_ALIASES.get(_strategy)

        # NOTE(flaper87): The next 3 lines help
        # with the migration to oslo.messaging.
        # Without them, gate tests won't know
        # what driver should be loaded.
        # Once this patch lands, devstack will be
        # updated and then these lines will be removed.
        url = None
        if _strategy in ['rabbit', 'qpid']:
            url = _strategy + '://'

        publisher_id = CONF.default_publisher_id
        self._transport = messaging.get_transport(CONF, url)
        self._notifier = messaging.Notifier(self._transport,
                                            driver=_driver,
                                            publisher_id=publisher_id)
예제 #6
0
def launch_monitor(transport):
    print "launching monitor"
    target = messaging.Target(
        topic=cfg.CONF.monitor.topic,
        server=cfg.CONF.monitor.host
    )

    notifier = messaging.Notifier(transport, cfg.CONF.agent.host, driver='messaging',
                                  topic=cfg.CONF.agent.notifications)

    monitor_engine = def_monitor.DefaultMonitor(rpc.get_agentclient(), notifier)

    monitor_endpoints = [rpc.MonitorServer(monitor_engine)]

    monitor_server = messaging.get_rpc_server(
        transport,
        target,
        monitor_endpoints,
        executor='eventlet'
    )

    try:
        monitor_server.start()
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print ("Stopping server")
    monitor_server.stop()
    monitor_server.wait()
예제 #7
0
def launch_agent(transport):
    print "launching agent"
    target = messaging.Target(
        topic=cfg.CONF.agent.topic,
        server=cfg.CONF.agent.host
    )

    notifier = messaging.Notifier(transport, cfg.CONF.monitor.host, driver='messaging',
                                  topic=cfg.CONF.monitor.notifications)

    agent_engine = def_agent.DefaultAgent(rpc.get_monitorclient(), notifier)
    agent_endpoints = [rpc.AgentServer(agent_engine)]

    agent_server = messaging.get_rpc_server(
        transport,
        target,
        agent_endpoints,
        executor='eventlet'
    )

    try:
        agent_server.start()
        while True:
            time.sleep(0)
    except KeyboardInterrupt:
        print ("Stopping server")
    agent_server.stop()

    agent_server.wait()
예제 #8
0
def init(conf):
    """Initialise the oslo.messaging layer."""
    global TRANSPORT, NOTIFIER
    messaging.set_transport_defaults('payload')
    TRANSPORT = messaging.get_transport(conf)
    serializer = RequestContextSerializer(None)
    NOTIFIER = messaging.Notifier(TRANSPORT, serializer=serializer)
예제 #9
0
 def _setup_notifier(self,
                     transport,
                     topic='testtopic',
                     publisher_id='testpublisher'):
     return messaging.Notifier(transport,
                               topic=topic,
                               driver='messaging',
                               publisher_id=publisher_id)
예제 #10
0
def init(conf):
    global NOTIFIER
    global TRANSPORT
    exmods = get_allowed_exmods()
    messaging.set_transport_defaults(control_exchange='nova_compute_agent')
    TRANSPORT = messaging.get_transport(conf, allowed_remote_exmods=exmods)
    serializer = RequestContextSerializer(JsonPayloadSerializer())
    NOTIFIER = messaging.Notifier(TRANSPORT, serializer=serializer)
예제 #11
0
def init(conf):
    global TRANSPORT, NOTIFIER
    exmods = get_allowed_exmods()
    TRANSPORT = messaging.get_transport(conf,
                                        allowed_remote_exmods=exmods,
                                        aliases=TRANSPORT_ALIASES)
    serializer = RequestContextSerializer()
    NOTIFIER = messaging.Notifier(TRANSPORT, serializer=serializer)
예제 #12
0
 def __init__(self, *args, **kwargs):
     # NOTE(dhellmann): Avoid a cyclical import by doing this one
     # at runtime.
     from oslo import messaging
     logging.Handler.__init__(self, *args, **kwargs)
     self._transport = messaging.get_transport(cfg.CONF)
     self._notifier = messaging.Notifier(self._transport,
                                         publisher_id='error.publisher')
 def initialize(self, environment):
     if StatusReporter.transport is None:
         StatusReporter.transport = \
             messaging.get_transport(config.CONF)
     self._notifier = messaging.Notifier(
         StatusReporter.transport,
         publisher_id=uuidutils.generate_uuid(),
         topic='murano')
     self._environment_id = environment.object_id
예제 #14
0
def init(conf):
    global TRANSPORT, NOTIFIER
    exmods = get_allowed_exmods()
    TRANSPORT = messaging.get_transport(conf,
                                        allowed_remote_exmods=exmods,
                                        aliases=TRANSPORT_ALIASES)

    #serializer = RequestContextSerializer(JsonPayloadSerializer())
    # https://review.openstack.org/#/c/71532/1/nova/rpc.py
    NOTIFIER = messaging.Notifier(TRANSPORT, serializer=None)
예제 #15
0
def init(conf):
    """
    初始化过程,实现三方面内容的初始化:
    1.确定xdrs异常类的基类的处理文件xdrs.exception;
    2.确定了使用rabbit这个AMQP的driver方式:
    3.加载notifier各种驱动实现方式:
      [oslo.messaging.notify.drivers]
      log = oslo.messaging.notify._impl_log:LogDriver
      messagingv2 = oslo.messaging.notify._impl_messaging:MessagingV2Driver
      noop = oslo.messaging.notify._impl_noop:NoOpDriver
      routing = oslo.messaging.notify._impl_routing:RoutingDriver
      test = oslo.messaging.notify._impl_test:TestDriver
      messaging = oslo.messaging.notify._impl_messaging:MessagingDriver
    """
    global TRANSPORT, NOTIFIER
    exmods = get_allowed_exmods()
    """
    exmods = ['xdrs.exception']
    这个方法实现了确定xdrs异常类的基类的处理文件;
    """
    
    TRANSPORT = messaging.get_transport(conf,
                                        allowed_remote_exmods=exmods,
                                        aliases=TRANSPORT_ALIASES)
    """
    ======================================================================================
    conf = <oslo.config.cfg.ConfigOpts object at 0x1ebf490>
    allowed_remote_exmods = ['xdrs.exception']
    aliases = {
              'nova.openstack.common.rpc.impl_kombu': 'rabbit'
              'nova.rpc.impl_kombu': 'rabbit', 
              }
    TRANSPORT = <oslo.messaging.transport.Transport object at 0x30b5150>
    ======================================================================================
    ======================================================================================
    返回值复制给TRANSPORT,实际上这里实现的就是确定了使用rabbit这个driver:
    mgr = <stevedore.driver.DriverManager object at 0x2d5a090>
    mgr.driver = <oslo.messaging._drivers.impl_rabbit.RabbitDriver object at 0x2dd90d0>
    Transport(mgr.driver) = <oslo.messaging.transport.Transport object at 0x311f210>
    TRANSPORT._driver = <oslo.messaging._drivers.impl_rabbit.RabbitDriver object at 0x3a000d0>
    ======================================================================================
    """
    serializer = RequestContextSerializer(JsonPayloadSerializer())
    """
    这里实现的是加载notifier各种驱动实现方式;
    [oslo.messaging.notify.drivers]
    log = oslo.messaging.notify._impl_log:LogDriver
    messagingv2 = oslo.messaging.notify._impl_messaging:MessagingV2Driver
    noop = oslo.messaging.notify._impl_noop:NoOpDriver
    routing = oslo.messaging.notify._impl_routing:RoutingDriver
    test = oslo.messaging.notify._impl_test:TestDriver
    messaging = oslo.messaging.notify._impl_messaging:MessagingDriver
    """
    NOTIFIER = messaging.Notifier(TRANSPORT, serializer=serializer)
예제 #16
0
    def __init__(self, strategy=None):

        _driver = None
        _strategy = strategy

        if CONF.notifier_strategy != 'default':
            msg = _("notifier_strategy was deprecated in "
                    "favor of `notification_driver`")
            LOG.warn(msg)

            # NOTE(flaper87): Use this to keep backwards
            # compatibility. We'll try to get an oslo.messaging
            # driver from the specified strategy.
            _strategy = strategy or CONF.notifier_strategy
            _driver = _STRATEGY_ALIASES.get(_strategy)

        publisher_id = CONF.default_publisher_id

        try:
            # NOTE(flaper87): Assume the user has configured
            # the transport url.
            self._transport = messaging.get_transport(CONF, aliases=_ALIASES)
        except messaging.DriverLoadFailure:
            # NOTE(flaper87): Catch driver load failures and re-raise
            # them *just* if the `transport_url` option was set. This
            # step is intended to keep backwards compatibility and avoid
            # weird behaviors (like exceptions on missing dependencies)
            # when the old notifier options are used.
            if CONF.transport_url is not None:
                with excutils.save_and_reraise_exception():
                    LOG.exception(_('Error loading the notifier'))

        # NOTE(flaper87): This needs to be checked
        # here because the `get_transport` call
        # registers `transport_url` into ConfigOpts.
        if not CONF.transport_url:
            # NOTE(flaper87): The next 3 lines help
            # with the migration to oslo.messaging.
            # Without them, gate tests won't know
            # what driver should be loaded.
            # Once this patch lands, devstack will be
            # updated and then these lines will be removed.
            url = None
            if _strategy in ['rabbit', 'qpid']:
                url = _strategy + '://'
            self._transport = messaging.get_transport(CONF,
                                                      url,
                                                      aliases=_ALIASES)

        self._notifier = messaging.Notifier(self._transport,
                                            driver=_driver,
                                            publisher_id=publisher_id)
예제 #17
0
    def test_emit_cfg_log_notifier_in_notifier_drivers(self):
        drivers = ['messaging', 'log']
        self.config(notification_driver=drivers)
        self.stub_flg = True

        transport = test_notifier._FakeTransport(self.conf)
        notifier = messaging.Notifier(transport)

        def fake_notifier(*args, **kwargs):
            self.stub_flg = False

        self.stubs.Set(notifier, 'error', fake_notifier)

        logrecord = logging.LogRecord(name='name', level='WARN',
                                      pathname='/tmp', lineno=1, msg='Message',
                                      args=None, exc_info=None)
        self.publisherrorshandler.emit(logrecord)
        self.assertTrue(self.stub_flg)
예제 #18
0
파일: notifier.py 프로젝트: zaina/glance
    def __init__(self, strategy=None):

        _driver = None
        _strategy = strategy

        if CONF.notifier_strategy != 'default':
            msg = _("notifier_strategy was deprecated in "
                    "favor of `notification_driver`")
            warnings.warn(msg, DeprecationWarning)

            # NOTE(flaper87): Use this to keep backwards
            # compatibility. We'll try to get an oslo.messaging
            # driver from the specified strategy.
            _strategy = strategy or CONF.notifier_strategy
            _driver = _STRATEGY_ALIASES.get(_strategy)

        publisher_id = CONF.default_publisher_id

        # NOTE(flaper87): Assume the user has configured
        # the transport url.
        self._transport = messaging.get_transport(CONF,
                                                  aliases=_ALIASES)

        # NOTE(flaper87): This needs to be checked
        # here because the `get_transport` call
        # registers `transport_url` into ConfigOpts.
        if not CONF.transport_url:
            # NOTE(flaper87): The next 3 lines help
            # with the migration to oslo.messaging.
            # Without them, gate tests won't know
            # what driver should be loaded.
            # Once this patch lands, devstack will be
            # updated and then these lines will be removed.
            url = None
            if _strategy in ['rabbit', 'qpid']:
                url = _strategy + '://'
            self._transport = messaging.get_transport(CONF, url,
                                                      aliases=_ALIASES)

        self._notifier = messaging.Notifier(self._transport,
                                            driver=_driver,
                                            publisher_id=publisher_id)
예제 #19
0
def _get_notifier():
    """Return a notifier object.

    If _notifier is None it means that a notifier object has not been set.
    If _notifier is False it means that a notifier has previously failed to
    construct.
    Otherwise it is a constructed Notifier object.
    """
    global _notifier

    if _notifier is None:
        host = CONF.default_publisher_id or socket.gethostname()
        try:
            transport = messaging.get_transport(CONF)
            _notifier = messaging.Notifier(transport, "identity.%s" % host)
        except Exception:
            LOG.exception(_LE("Failed to construct notifier"))
            _notifier = False

    return _notifier
예제 #20
0
파일: rpc.py 프로젝트: xinw1012/sahara
def setup(url=None, optional=False):
    """Initialise the oslo.messaging layer."""
    global TRANSPORT, NOTIFIER, SERIALIZER

    if not cfg.CONF.enable_notifications:
        LOG.info(_LI("Notifications disabled"))
        return
    LOG.info(_LI("Notifications enabled"))

    messaging.set_transport_defaults('sahara')

    SERIALIZER = ContextSerializer(JsonPayloadSerializer())

    try:
        TRANSPORT = messaging.get_transport(cfg.CONF, url, aliases=_ALIASES)
    except messaging.InvalidTransportURL as e:
        TRANSPORT = None
        if not optional or e.url:
            raise

    if TRANSPORT:
        NOTIFIER = messaging.Notifier(TRANSPORT, serializer=SERIALIZER)
예제 #21
0
    def test_serializer(self, mock_utcnow):
        transport = _FakeTransport(self.conf)

        serializer = msg_serializer.NoOpSerializer()

        notifier = messaging.Notifier(transport,
                                      'test.localhost',
                                      driver='test',
                                      topic='test',
                                      serializer=serializer)

        message_id = uuid.uuid4()
        self.mox.StubOutWithMock(uuid, 'uuid4')
        uuid.uuid4().AndReturn(message_id)

        mock_utcnow.return_value = datetime.datetime.utcnow()

        self.mox.StubOutWithMock(serializer, 'serialize_context')
        self.mox.StubOutWithMock(serializer, 'serialize_entity')
        serializer.serialize_context(dict(user='******')).\
            AndReturn(dict(user='******'))
        serializer.serialize_entity(dict(user='******'), 'bar').AndReturn('sbar')

        self.mox.ReplayAll()

        notifier.info(dict(user='******'), 'test.notify', 'bar')

        message = {
            'message_id': str(message_id),
            'publisher_id': 'test.localhost',
            'event_type': 'test.notify',
            'priority': 'INFO',
            'payload': 'sbar',
            'timestamp': str(timeutils.utcnow()),
        }

        self.assertEqual([(dict(user='******'), message, 'INFO', None)],
                         _impl_test.NOTIFICATIONS)
예제 #22
0
# coding: utf-8

import logging
import uuid

from oslo.config import cfg
from oslo import messaging

logging.basicConfig()
log = logging.getLogger()

log.addHandler(logging.StreamHandler())
log.setLevel(logging.INFO)

transport_url = 'rabbit://*****:*****@127.0.0.1:5672/'
transport = messaging.get_transport(cfg.CONF, transport_url)

driver = 'messaging'

notifier = messaging.Notifier(transport,
                              driver=driver,
                              publisher_id='testing',
                              topic='monitor')

notifier.info({'some': 'context'}, 'compute.create_instance',
              {'heavy': 'payload'})
notifier.error({'some': 'context'}, 'compute.create_instance',
               {'heavy': 'payload'})
notifier.warn({'some': 'context'}, 'compute.create_instance',
              {'heavy': 'payload'})
예제 #23
0
파일: notifier.py 프로젝트: amoid/glance
 def __init__(self):
     publisher_id = CONF.default_publisher_id
     self._transport = get_transport()
     self._notifier = messaging.Notifier(self._transport,
                                         publisher_id=publisher_id)
예제 #24
0
 def __init__(self):
     publisher_id = CONF.default_publisher_id
     self._transport = messaging.get_transport(CONF, aliases=_ALIASES)
     self._notifier = messaging.Notifier(self._transport,
                                         publisher_id=publisher_id)
예제 #25
0
파일: notifier.py 프로젝트: jakecoll/blazar
def init():
    global TRANSPORT, NOTIFIER
    TRANSPORT = messaging.get_transport(CONF)
    NOTIFIER = messaging.Notifier(TRANSPORT,
                                  publisher_id=CONF.notifications.publisher_id)
예제 #26
0
from oslo.config import cfg
from oslo import messaging

CONF = cfg.CONF
transport = messaging.get_transport(CONF,
                                    url='rabbit://*****:*****@localhost:5672/')
notifier = messaging.Notifier(transport,
                              "ajaya",
                              driver='messaging',
                              topic='mdb')
context = {}
payload = {"a": "b"}
import pdb
pdb.set_trace()
notifier.warn(context, "hi", payload)