Python oslo_messaging.Notifier() Examples

The following are 30 code examples of oslo_messaging.Notifier(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oslo_messaging , or try the search function .
Example #1
Source File: rpc.py    From neutron-lib with Apache License 2.0 6 votes vote down vote up
def init(conf, rpc_ext_mods=None):
    """Initialize the global RPC objects.

    :param conf: The oslo conf to use for initialization.
    :param rpc_ext_mods: Exception modules to expose via RPC.
    :returns: None.
    """
    global TRANSPORT, NOTIFICATION_TRANSPORT, NOTIFIER

    if rpc_ext_mods is None:
        rpc_ext_mods = _DFT_EXMODS
    else:
        rpc_ext_mods = list(set(rpc_ext_mods + _DFT_EXMODS))

    TRANSPORT = oslo_messaging.get_rpc_transport(
        conf, allowed_remote_exmods=rpc_ext_mods)
    NOTIFICATION_TRANSPORT = oslo_messaging.get_notification_transport(
        conf, allowed_remote_exmods=rpc_ext_mods)
    serializer = RequestContextSerializer()
    NOTIFIER = oslo_messaging.Notifier(NOTIFICATION_TRANSPORT,
                                       serializer=serializer) 
Example #2
Source File: test_action_notification.py    From watcher with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(TestActionNotification, self).setUp()
        p_get_notifier = mock.patch.object(rpc, 'get_notifier')
        m_get_notifier = p_get_notifier.start()
        self.addCleanup(p_get_notifier.stop)
        self.m_notifier = mock.Mock(spec=om.Notifier)

        def fake_get_notifier(publisher_id):
            self.m_notifier.publisher_id = publisher_id
            return self.m_notifier

        m_get_notifier.side_effect = fake_get_notifier
        self.goal = utils.create_test_goal(mock.Mock())
        self.strategy = utils.create_test_strategy(mock.Mock())
        self.audit = utils.create_test_audit(mock.Mock(),
                                             strategy_id=self.strategy.id)
        self.action_plan = utils.create_test_action_plan(mock.Mock()) 
Example #3
Source File: notifier.py    From vitrage with Apache License 2.0 6 votes vote down vote up
def _get_topics(self):
        topics = []

        try:
            notifier_topic = CONF.entity_graph.notifier_topic
            notifier_plugins = CONF.notifiers
            if notifier_topic and notifier_plugins:
                topics.append(notifier_topic)
        except Exception:
            LOG.exception('Graph Notifier - missing configuration')

        try:
            machine_learning_topic = \
                CONF.machine_learning.machine_learning_topic
            machine_learning_plugins = CONF.machine_learning.plugins
            if machine_learning_topic and machine_learning_plugins:
                topics.append(machine_learning_topic)
        except Exception:
            LOG.info('Machine Learning - missing configuration')

        return topics 
Example #4
Source File: notifier.py    From vitrage with Apache License 2.0 6 votes vote down vote up
def __init__(self, ):
        self.oslo_notifiers = {}
        try:
            notifier_plugins = CONF.notifiers

            LOG.debug('notifier_plugins: %s', notifier_plugins)

            if not notifier_plugins:
                LOG.info('Evaluator Notifier is disabled')
                return

            topic_prefix = \
                CONF.evaluator_actions.evaluator_notification_topic_prefix

            for notifier in notifier_plugins:
                LOG.debug('Adding evaluator notifier %s', notifier)

                self.oslo_notifiers[notifier] = oslo_messaging.Notifier(
                    get_transport(),
                    driver='messagingv2',
                    publisher_id='vitrage.evaluator',
                    topics=[topic_prefix + '.' + notifier])

        except Exception:
            LOG.exception('Evaluator Notifier - missing configuration') 
Example #5
Source File: test_event.py    From aodh with Apache License 2.0 6 votes vote down vote up
def test_batch_event_listener(self, mocked):
        msg_notifier = oslo_messaging.Notifier(
            self.transport, topics=['alarm.all'], driver='messaging',
            publisher_id='test-publisher')

        received_events = []
        mocked.side_effect = lambda msg: received_events.append(msg)
        event1 = {'event_type': 'compute.instance.update',
                  'traits': ['foo', 'bar'],
                  'message_id': '20d03d17-4aba-4900-a179-dba1281a3451',
                  'generated': '2016-04-23T06:50:21.622739'}
        event2 = {'event_type': 'compute.instance.update',
                  'traits': ['foo', 'bar'],
                  'message_id': '20d03d17-4aba-4900-a179-dba1281a3452',
                  'generated': '2016-04-23T06:50:23.622739'}
        msg_notifier.sample({}, 'event', event1)
        msg_notifier.sample({}, 'event', event2)

        svc = event.EventAlarmEvaluationService(0, self.CONF)
        self.addCleanup(svc.terminate)

        time.sleep(1)
        self.assertEqual(1, len(received_events))
        self.assertEqual(2, len(received_events[0])) 
Example #6
Source File: rpc.py    From manila with Apache License 2.0 6 votes vote down vote up
def init(conf):
    global TRANSPORT, NOTIFICATION_TRANSPORT, NOTIFIER
    exmods = get_allowed_exmods()
    TRANSPORT = messaging.get_rpc_transport(conf,
                                            allowed_remote_exmods=exmods)
    NOTIFICATION_TRANSPORT = messaging.get_notification_transport(
        conf,
        allowed_remote_exmods=exmods)

    if utils.notifications_enabled(conf):
        json_serializer = messaging.JsonPayloadSerializer()
        serializer = RequestContextSerializer(json_serializer)
        NOTIFIER = messaging.Notifier(NOTIFICATION_TRANSPORT,
                                      serializer=serializer)
    else:
        NOTIFIER = utils.DO_NOTHING 
Example #7
Source File: rpc.py    From karbor with Apache License 2.0 6 votes vote down vote up
def init(conf):

    global TRANSPORT, NOTIFICATION_TRANSPORT, NOTIFIER
    exmods = get_allowed_exmods()
    TRANSPORT = messaging.get_rpc_transport(conf,
                                            allowed_remote_exmods=exmods)
    NOTIFICATION_TRANSPORT = messaging.get_notification_transport(
        conf,
        allowed_remote_exmods=exmods)

    # get_notification_transport has loaded oslo_messaging_notifications config
    # group, so we can now check if notifications are actually enabled.
    if utils.notifications_enabled(conf):
        json_serializer = messaging.JsonPayloadSerializer()
        serializer = RequestContextSerializer(json_serializer)
        NOTIFIER = messaging.Notifier(NOTIFICATION_TRANSPORT,
                                      serializer=serializer)
    else:
        NOTIFIER = utils.DO_NOTHING 
Example #8
Source File: test_notifier.py    From aodh with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestAlarmNotifier, self).setUp()
        conf = service.prepare_service(argv=[], config_files=[])
        self.CONF = self.useFixture(fixture_config.Config(conf)).conf
        self.setup_messaging(self.CONF)
        self._msg_notifier = oslo_messaging.Notifier(
            self.transport, topics=['alarming'], driver='messaging',
            publisher_id='testpublisher')
        self.zaqar = FakeZaqarClient(self)
        self.useFixture(fixtures.MockPatch(
            'aodh.notifier.zaqar.ZaqarAlarmNotifier.get_zaqar_client',
            return_value=self.zaqar))
        self.service = notifier.AlarmNotifierService(0, self.CONF)
        self.addCleanup(self.service.terminate) 
Example #9
Source File: queue.py    From aodh with Apache License 2.0 5 votes vote down vote up
def __init__(self, conf):
        self.notifier = oslo_messaging.Notifier(
            messaging.get_transport(conf),
            driver='messagingv2',
            publisher_id="alarming.evaluator",
            topics=[conf.notifier_topic]) 
Example #10
Source File: messaging.py    From aodh with Apache License 2.0 5 votes vote down vote up
def get_notifier(transport, publisher_id):
    """Return a configured oslo_messaging notifier."""
    notifier = oslo_messaging.Notifier(transport, serializer=_SERIALIZER)
    return notifier.prepare(publisher_id=publisher_id) 
Example #11
Source File: rpc.py    From cyborg with Apache License 2.0 5 votes vote down vote up
def init(conf):
    global TRANSPORT, NOTIFICATION_TRANSPORT, NOTIFIER
    exmods = get_allowed_exmods()
    TRANSPORT = messaging.get_rpc_transport(conf,
                                            allowed_remote_exmods=exmods)
    NOTIFICATION_TRANSPORT = messaging.get_notification_transport(
        conf,
        allowed_remote_exmods=exmods)
    serializer = RequestContextSerializer(messaging.JsonPayloadSerializer())
    NOTIFIER = messaging.Notifier(NOTIFICATION_TRANSPORT,
                                  serializer=serializer,
                                  topics=['notifications']) 
Example #12
Source File: messaging.py    From senlin with Apache License 2.0 5 votes vote down vote up
def setup(url=None, optional=False):
    """Initialise the oslo_messaging layer."""
    global TRANSPORT, GLOBAL_TRANSPORT, NOTIFIER

    if url and url.startswith("fake://"):
        # NOTE: oslo_messaging fake driver uses time.sleep
        # for task switch, so we need to monkey_patch it
        eventlet.monkey_patch(time=True)

    messaging.set_transport_defaults('senlin')
    if not TRANSPORT:
        exmods = ['senlin.common.exception']
        try:
            TRANSPORT = messaging.get_rpc_transport(
                cfg.CONF, url, allowed_remote_exmods=exmods)
        except messaging.InvalidTransportURL as e:
            TRANSPORT = None
            if not optional or e.url:
                # NOTE: oslo_messaging is configured but unloadable
                # so reraise the exception
                raise

    if not NOTIFIER:
        exmods = ['senlin.common.exception']
        try:
            NOTIFICATION_TRANSPORT = messaging.get_notification_transport(
                cfg.CONF, allowed_remote_exmods=exmods)
        except Exception:
            raise

        serializer = RequestContextSerializer(JsonPayloadSerializer())
        NOTIFIER = messaging.Notifier(NOTIFICATION_TRANSPORT,
                                      serializer=serializer,
                                      topics=cfg.CONF.notification_topics) 
Example #13
Source File: rpc.py    From watcher with Apache License 2.0 5 votes vote down vote up
def init(conf):
    global TRANSPORT, NOTIFICATION_TRANSPORT, NOTIFIER
    exmods = get_allowed_exmods()
    TRANSPORT = messaging.get_rpc_transport(
        conf, allowed_remote_exmods=exmods)
    NOTIFICATION_TRANSPORT = messaging.get_notification_transport(
        conf, allowed_remote_exmods=exmods)

    serializer = RequestContextSerializer(JsonPayloadSerializer())
    if not conf.notification_level:
        NOTIFIER = messaging.Notifier(
            NOTIFICATION_TRANSPORT, serializer=serializer, driver='noop')
    else:
        NOTIFIER = messaging.Notifier(NOTIFICATION_TRANSPORT,
                                      serializer=serializer) 
Example #14
Source File: test_audit_notification.py    From watcher with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestAuditNotification, self).setUp()
        p_get_notifier = mock.patch.object(rpc, 'get_notifier')
        m_get_notifier = p_get_notifier.start()
        self.addCleanup(p_get_notifier.stop)
        self.m_notifier = mock.Mock(spec=om.Notifier)

        def fake_get_notifier(publisher_id):
            self.m_notifier.publisher_id = publisher_id
            return self.m_notifier

        m_get_notifier.side_effect = fake_get_notifier
        self.goal = utils.create_test_goal(mock.Mock())
        self.strategy = utils.create_test_strategy(mock.Mock()) 
Example #15
Source File: test_service_notifications.py    From watcher with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestActionPlanNotification, self).setUp()
        p_get_notifier = mock.patch.object(rpc, 'get_notifier')
        m_get_notifier = p_get_notifier.start()
        self.addCleanup(p_get_notifier.stop)
        self.m_notifier = mock.Mock(spec=om.Notifier)

        def fake_get_notifier(publisher_id):
            self.m_notifier.publisher_id = publisher_id
            return self.m_notifier

        m_get_notifier.side_effect = fake_get_notifier 
Example #16
Source File: test_action_plan_notification.py    From watcher with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestActionPlanNotification, self).setUp()
        p_get_notifier = mock.patch.object(rpc, 'get_notifier')
        m_get_notifier = p_get_notifier.start()
        self.addCleanup(p_get_notifier.stop)
        self.m_notifier = mock.Mock(spec=om.Notifier)

        def fake_get_notifier(publisher_id):
            self.m_notifier.publisher_id = publisher_id
            return self.m_notifier

        m_get_notifier.side_effect = fake_get_notifier
        self.goal = utils.create_test_goal(mock.Mock())
        self.audit = utils.create_test_audit(mock.Mock(), interval=None)
        self.strategy = utils.create_test_strategy(mock.Mock()) 
Example #17
Source File: zabbix_vitrage.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('sendto', help='Vitrage message bus path')
    parser.add_argument('topic', help='zabbix topic')
    parser.add_argument('body', help='zabbix body')
    args = parser.parse_args()

    logging.info('SENDTO: %s', args.sendto)
    logging.info('TOPIC: %s', args.topic)
    logging.info('BODY:\n----\n%s\n', args.body)

    transport_url = args.sendto
    transport = messaging.get_notification_transport(cfg.CONF, transport_url)
    driver = 'messagingv2'
    publisher = 'zabbix_%s' % socket.gethostname()
    notifier = messaging.Notifier(transport,
                                  driver=driver,
                                  publisher_id=publisher,
                                  topics=['vitrage_notifications'])

    alarm_status = args.topic.lower()
    event_type = '%s.%s' % (ZABBIX_EVENT_TYPE, alarm_status)
    payload = create_payload(args.body)

    logging.info('PUBLISHER: %s', publisher)
    logging.info('EVENT_TYPE: %s', event_type)
    logging.info('\nPAYLOAD:\n%s', payload)
    notifier.info(ctxt={'message_id': uuidutils.generate_uuid(),
                        'publisher_id': publisher,
                        'timestamp': datetime.utcnow()},
                  event_type=event_type,
                  payload=payload)
    logging.info('MESSAGE SENT..') 
Example #18
Source File: rpc.py    From tacker with Apache License 2.0 5 votes vote down vote up
def init(conf):
    global TRANSPORT, NOTIFICATION_TRANSPORT, NOTIFIER
    exmods = get_allowed_exmods()
    TRANSPORT = oslo_messaging.get_rpc_transport(conf,
                                                 allowed_remote_exmods=exmods)
    NOTIFICATION_TRANSPORT = oslo_messaging.get_notification_transport(
        conf, allowed_remote_exmods=exmods)
    json_serializer = oslo_messaging.JsonPayloadSerializer()
    serializer = RequestContextSerializer(json_serializer)
    NOTIFIER = oslo_messaging.Notifier(NOTIFICATION_TRANSPORT,
                                       serializer=serializer) 
Example #19
Source File: rpc.py    From designate with Apache License 2.0 5 votes vote down vote up
def init(conf):
    global TRANSPORT, NOTIFIER, NOTIFICATION_TRANSPORT
    exmods = get_allowed_exmods()
    TRANSPORT = create_transport(get_transport_url())
    NOTIFICATION_TRANSPORT = messaging.get_notification_transport(
        conf, allowed_remote_exmods=exmods)
    serializer = RequestContextSerializer(JsonPayloadSerializer())
    NOTIFIER = messaging.Notifier(NOTIFICATION_TRANSPORT,
                                  serializer=serializer) 
Example #20
Source File: vitrageplugin.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def initialize(self):
        """Set up the Vitrage API client and add the notification callback. """

        url = self.config['transport_url']
        transport = messaging.get_notification_transport(cfg.CONF, url)
        self.notifier = messaging.Notifier(transport,
                                           driver='messagingv2',
                                           publisher_id=COLLECTD_DATASOURCE,
                                           topics=['vitrage_notifications'])
        self.add_notification_callback(self.notify) 
Example #21
Source File: kapacitor_vitrage.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('sendto', help='url')
    args = parser.parse_args()
    data = sys.stdin.readlines()[0]
    transport_url = args.sendto
    transport = messaging.get_notification_transport(cfg.CONF, transport_url)

    driver = 'messagingv2'
    publisher = 'kapacitor_%s' % socket.gethostname()
    notifier = messaging.Notifier(transport,
                                  driver=driver,
                                  publisher_id=publisher,
                                  topics=['vitrage_notifications'])
    alarm = json.loads(data)
    host = alarm['data']['series'][0]['tags']['host']
    priority = alarm['level'].lower()
    alarm.update({'host': host,
                  'priority': priority})
    alarm.pop('data', None)
    alarm_status = alarm['level'].lower()
    event_type = '%s.%s' % (KAPACITOR_EVENT_TYPE, alarm_status)
    logging.info('Send to: %s', transport_url)
    logging.info('BODY:\n----\n%s\n', data)
    logging.info('PUBLISHER: %s', publisher)
    logging.info('EVENT_TYPE: %s', event_type)
    logging.info('\nALARM:\n%s', alarm)
    notifier.info(ctxt={'message_id': uuidutils.generate_uuid(),
                        'publisher_id': publisher},
                  event_type=event_type,
                  payload=alarm)
    logging.info('MESSAGE SENT..') 
Example #22
Source File: notifier.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.oslo_notifier = None
        topics = [CONF.persistency.persistor_topic]
        self.oslo_notifier = oslo_messaging.Notifier(
            get_transport(),
            driver='messagingv2',
            publisher_id='vitrage.graph',
            topics=topics) 
Example #23
Source File: service.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def _init_oslo_notifier(self):
        self.oslo_notifier = None
        try:
            self.publisher = 'vitrage-snmp-parsing'
            self.oslo_notifier = oslo_messaging.Notifier(
                get_transport(),
                driver='messagingv2',
                publisher_id=self.publisher,
                topics=['vitrage_notifications'])
        except Exception:
            LOG.exception('Failed to initialize oslo notifier') 
Example #24
Source File: messaging.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def notify(self, event_type, data):
        LOG.debug('notify : ' + event_type + ' ' + str(data))
        if self.notifier:
            try:
                self.notifier.info({}, event_type, data)
            except Exception:
                LOG.exception('Notifier cannot notify.')
        else:
            LOG.error('Notifier cannot notify') 
Example #25
Source File: messaging.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def __init__(self, publisher_id, topics):
        transport = get_transport()
        self.notifier = oslo_msg.Notifier(
            transport,
            driver='messagingv2',
            publisher_id=publisher_id,
            topics=topics) 
Example #26
Source File: load_generator.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def __init__(self, worker_id):
        super(StressNotificationsService, self).__init__(worker_id)
        self.oslo_notifier = None
        topics = CONF.datasources.notification_topics
        self.oslo_notifier = oslo_messaging.Notifier(
            get_transport(),
            driver='messagingv2',
            publisher_id='vitrage.stress',
            topics=topics)
        self.periodic = periodics.PeriodicWorker.create(
            [], executor_factory=lambda: ThreadPoolExecutor(max_workers=10)) 
Example #27
Source File: rpc.py    From masakari with Apache License 2.0 5 votes vote down vote up
def init(conf):
    global TRANSPORT, NOTIFICATION_TRANSPORT, NOTIFIER
    exmods = get_allowed_exmods()

    TRANSPORT = create_transport(get_transport_url())
    NOTIFICATION_TRANSPORT = messaging.get_notification_transport(
        conf, allowed_remote_exmods=exmods)
    serializer = RequestContextSerializer(JsonPayloadSerializer())
    NOTIFIER = messaging.Notifier(NOTIFICATION_TRANSPORT,
                                  serializer=serializer,
                                  topics=['versioned_notifications']) 
Example #28
Source File: rpc.py    From magnum with Apache License 2.0 5 votes vote down vote up
def init(conf):
    global TRANSPORT, NOTIFIER
    exmods = get_allowed_exmods()
    TRANSPORT = messaging.get_rpc_transport(conf,
                                            allowed_remote_exmods=exmods)
    serializer = RequestContextSerializer(JsonPayloadSerializer())
    NOTIFIER = messaging.Notifier(TRANSPORT, serializer=serializer) 
Example #29
Source File: notifier.py    From searchlight with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        publisher_id = CONF.default_publisher_id
        self._transport = get_transport()
        self._notifier = oslo_messaging.Notifier(self._transport,
                                                 publisher_id=publisher_id) 
Example #30
Source File: test_rpc.py    From masakari with Apache License 2.0 4 votes vote down vote up
def _test_init(self, mock_notif, mock_noti_trans, mock_ser,
                   mock_exmods, notif_format, expected_driver_topic_kwargs,
                   versioned_notification_topics=['versioned_notifications']):
        notifier = mock.Mock()
        notif_transport = mock.Mock()
        transport = mock.Mock()
        serializer = mock.Mock()
        conf = mock.Mock()

        conf.transport_url = None
        conf.notification_format = notif_format
        mock_exmods.return_value = ['foo']
        conf.notifications.versioned_notifications_topics = (
            versioned_notification_topics)
        mock_noti_trans.return_value = notif_transport
        mock_ser.return_value = serializer
        mock_notif.side_effect = [notifier]

        @mock.patch.object(rpc, 'CONF', new=conf)
        @mock.patch.object(rpc, 'create_transport')
        @mock.patch.object(rpc, 'get_transport_url')
        def _test(get_url, create_transport):
            create_transport.return_value = transport
            rpc.init(conf)
            create_transport.assert_called_once_with(get_url.return_value)

        _test()

        self.assertTrue(mock_exmods.called)
        self.assertIsNotNone(rpc.TRANSPORT)
        self.assertIsNotNone(rpc.NOTIFIER)
        self.assertEqual(notifier, rpc.NOTIFIER)

        expected_calls = []
        for kwargs in expected_driver_topic_kwargs:
            expected_kwargs = {'serializer': serializer}
            expected_kwargs.update(kwargs)
            expected_calls.append(((notif_transport,), expected_kwargs))

        self.assertEqual(expected_calls, mock_notif.call_args_list,
                         "The calls to messaging.Notifier() did not create "
                         "the versioned notifiers properly.")