Esempio n. 1
0
    def publish_counter(env, bytes_received, bytes_sent):
        req = Request(env)
        version, account, container, obj = split_path(req.path, 1, 4, True)
        now = timeutils.utcnow().isoformat()

        if bytes_received:
            publish.publish_counter(context.get_admin_context(),
                                    counter.Counter(
                                        name='storage.objects.incoming.bytes',
                                        type='delta',
                                        unit='B',
                                        volume=bytes_received,
                                        user_id=env.get('HTTP_X_USER_ID'),
                                        project_id=env.get('HTTP_X_TENANT_ID'),
                                        resource_id=account.partition(
                                            'AUTH_')[2],
                                        timestamp=now,
                                        resource_metadata={
                                            "path": req.path,
                                            "version": version,
                                            "container": container,
                                            "object": obj,
                                        },
                                    ),
                                    cfg.CONF.metering_topic,
                                    cfg.CONF.metering_secret,
                                    cfg.CONF.counter_source)

        if bytes_sent:
            publish.publish_counter(context.get_admin_context(),
                                    counter.Counter(
                                        name='storage.objects.outgoing.bytes',
                                        type='delta',
                                        unit='B',
                                        volume=bytes_sent,
                                        user_id=env.get('HTTP_X_USER_ID'),
                                        project_id=env.get('HTTP_X_TENANT_ID'),
                                        resource_id=account.partition(
                                            'AUTH_')[2],
                                        timestamp=now,
                                        resource_metadata={
                                            "path": req.path,
                                            "version": version,
                                            "container": container,
                                            "object": obj,
                                        }),
                                    cfg.CONF.metering_topic,
                                    cfg.CONF.metering_secret,
                                    cfg.CONF.counter_source)
Esempio n. 2
0
 def publish_counter(counter):
     """Create a metering message for the counter and publish it."""
     ctxt = context.get_admin_context()
     publish.publish_counter(ctxt, counter,
                             cfg.CONF.metering_topic,
                             cfg.CONF.metering_secret,
                             cfg.CONF.counter_source)
Esempio n. 3
0
 def setUp(self):
     super(TestFloatingIPPollster, self).setUp()
     self.context = context.get_admin_context()
     self.manager = manager.AgentManager()
     self.pollster = floatingip.FloatingIPPollster()
     self.stubs.Set(nova_client.Client, 'floating_ip_get_all',
                    self.faux_get_ips)
Esempio n. 4
0
    def publish_sample(self, env, bytes_received, bytes_sent):
        req = REQUEST.Request(env)
        try:
            version, account, container, obj = utils.split_path(req.path, 2,
                                                                4, True)
        except ValueError:
            return
        now = timeutils.utcnow().isoformat()

        resource_metadata = {
            "path": req.path,
            "version": version,
            "container": container,
            "object": obj,
        }

        for header in self.metadata_headers:
            if header.upper() in req.headers:
                resource_metadata['http_header_%s' % header] = req.headers.get(
                    header.upper())

        with self.pipeline_manager.publisher(
                context.get_admin_context()) as publisher:
            if bytes_received:
                publisher([sample.Sample(
                    name='storage.objects.incoming.bytes',
                    type=sample.TYPE_DELTA,
                    unit='B',
                    volume=bytes_received,
                    user_id=env.get('HTTP_X_USER_ID'),
                    project_id=env.get('HTTP_X_TENANT_ID'),
                    resource_id=account.partition('AUTH_')[2],
                    timestamp=now,
                    resource_metadata=resource_metadata)])

            if bytes_sent:
                publisher([sample.Sample(
                    name='storage.objects.outgoing.bytes',
                    type=sample.TYPE_DELTA,
                    unit='B',
                    volume=bytes_sent,
                    user_id=env.get('HTTP_X_USER_ID'),
                    project_id=env.get('HTTP_X_TENANT_ID'),
                    resource_id=account.partition('AUTH_')[2],
                    timestamp=now,
                    resource_metadata=resource_metadata)])

            # publish the event for each request
            # request method will be recorded in the metadata
            resource_metadata['method'] = req.method.lower()
            publisher([sample.Sample(
                name='storage.api.request',
                type=sample.TYPE_DELTA,
                unit='request',
                volume=1,
                user_id=env.get('HTTP_X_USER_ID'),
                project_id=env.get('HTTP_X_TENANT_ID'),
                resource_id=account.partition('AUTH_')[2],
                timestamp=now,
                resource_metadata=resource_metadata)])
Esempio n. 5
0
 def setUp(self):
     super(TestFloatingIPPollster, self).setUp()
     self.stubs = self.useFixture(moxstubout.MoxStubout()).stubs
     self.context = context.get_admin_context()
     self.manager = manager.AgentManager()
     self.pollster = floatingip.FloatingIPPollster()
     self.stubs.Set(nova_client.Client, "floating_ip_get_all", self.faux_get_ips)
Esempio n. 6
0
 def setUp(self):
     super(TestEnergyPollster, self).setUp()
     self.stubs = self.useFixture(moxstubout.MoxStubout()).stubs
     self.context = context.get_admin_context()
     self.manager = TestManager()
     self.stubs.Set(kwapi._Base, '_iter_probes',
                    self.fake_iter_probes)
Esempio n. 7
0
 def setUp(self):
     super(TestImagePollster, self).setUp()
     self.context = context.get_admin_context()
     self.manager = TestManager()
     self.useFixture(mockpatch.PatchObject(
         glance._Base, 'get_glance_client',
         side_effect=self.fake_get_glance_client))
Esempio n. 8
0
 def _process_notification_for_ext(self, ext, notification):
     handler = ext.obj
     if notification["event_type"] in handler.get_event_types():
         ctxt = context.get_admin_context()
         with self.pipeline_manager.publisher(ctxt, cfg.CONF.counter_source) as p:
             # FIXME(dhellmann): Spawn green thread?
             p(list(handler.process_notification(notification)))
Esempio n. 9
0
 def setUp(self):
     super(TestImagePollster, self).setUp()
     self.stubs = self.useFixture(moxstubout.MoxStubout()).stubs
     self.context = context.get_admin_context()
     self.manager = TestManager()
     self.stubs.Set(glance._Base, 'get_glance_client',
                    self.fake_get_glance_client)
Esempio n. 10
0
 def test_notify_alarm_log_action(self):
     self.service.notify_alarm(context.get_admin_context(),
                               {
                                   'actions': ['log://'],
                                   'alarm': {'name': 'foobar'},
                                   'condition': {'threshold': 42},
                               })
Esempio n. 11
0
    def test_notify_alarm_rest_action_with_ssl_verify_disable(self):
        action = 'https://host/action?ceilometer-alarm-ssl-verify=0'

        with mock.patch('eventlet.spawn_n', self._fake_spawn_n):
            with mock.patch.object(requests, 'post') as poster:
                self.service.notify_alarm(context.get_admin_context(),
                                          self._notification(action))
                poster.assert_called_with(action, data=DATA_JSON, verify=False)
Esempio n. 12
0
 def notify(self, alarm, state, reason):
     actions = getattr(alarm, Alarm.ALARM_ACTIONS_MAP[alarm.state])
     msg = self.make_msg('notify_alarm', data={
         'actions': actions,
         'alarm': alarm.alarm_id,
         'state': state,
         'reason': reason})
     self.cast(context.get_admin_context(), msg)
Esempio n. 13
0
 def setUp(self):
     super(TestImagePollsterPageSize, self).setUp()
     self.context = context.get_admin_context()
     self.manager = TestManager()
     self.useFixture(
         mockpatch.PatchObject(glance._Base, "get_glance_client", side_effect=self.fake_get_glance_client)
     )
     self.CONF = self.useFixture(fixture_config.Config()).conf
Esempio n. 14
0
 def presence(self, uuid, priority):
     cctxt = self.client.prepare(fanout=True)
     return cctxt.cast(context.get_admin_context(),
                       'presence',
                       data={
                           'uuid': uuid,
                           'priority': priority
                       })
Esempio n. 15
0
 def setUp(self):
     super(_BaseTestLBPollster, self).setUp()
     self.addCleanup(mock.patch.stopall)
     self.context = context.get_admin_context()
     self.manager = manager.AgentManager()
     plugin._get_keystone = mock.Mock()
     plugin._get_keystone.service_catalog.get_endpoints = mock.MagicMock(
         return_value={'network': mock.ANY})
Esempio n. 16
0
 def _process_notification_for_ext(self, ext, notification):
     handler = ext.obj
     if notification['event_type'] in handler.get_event_types():
         ctxt = context.get_admin_context()
         with self.pipeline_manager.publisher(ctxt,
                                              cfg.CONF.counter_source) as p:
             # FIXME(dhellmann): Spawn green thread?
             p(list(handler.process_notification(notification)))
Esempio n. 17
0
 def setUp(self):
     super(TestEnergyPollster, self).setUp()
     self.context = context.get_admin_context()
     self.manager = TestManager()
     self.useFixture(
         PatchObject(kwapi._Base,
                     '_iter_probes',
                     side_effect=self.fake_iter_probes))
Esempio n. 18
0
 def setUp(self):
     super(TestFloatingIPPollster, self).setUp()
     self.stubs = self.useFixture(moxstubout.MoxStubout()).stubs
     self.context = context.get_admin_context()
     self.manager = manager.AgentManager()
     self.pollster = floatingip.FloatingIPPollster()
     self.stubs.Set(nova_client.Client, 'floating_ip_get_all',
                    self.faux_get_ips)
Esempio n. 19
0
 def setUp(self):
     super(_BaseTestVPNPollster, self).setUp()
     self.addCleanup(mock.patch.stopall)
     self.context = context.get_admin_context()
     self.manager = manager.AgentManager()
     cli.Client.keystone = mock.Mock()
     cli.Client.keystone.service_catalog.get_endpoints = mock.Mock(
         return_value={'network': mock.ANY})
Esempio n. 20
0
 def allocate(self, uuid, alarms):
     cctxt = self.client.prepare(fanout=True)
     return cctxt.cast(context.get_admin_context(),
                       'allocate',
                       data={
                           'uuid': uuid,
                           'alarms': alarms
                       })
Esempio n. 21
0
    def test_notify_alarm_rest_action_ok(self):
        action = 'http://host/action'

        with mock.patch('eventlet.spawn_n', self._fake_spawn_n):
            with mock.patch.object(requests, 'post') as poster:
                self.service.notify_alarm(context.get_admin_context(),
                                          self._notification(action))
                poster.assert_called_with(action, data=DATA_JSON)
Esempio n. 22
0
 def setUp(self):
     super(TestImagePollsterPageSize, self).setUp()
     self.context = context.get_admin_context()
     self.manager = TestManager()
     self.useFixture(mockpatch.PatchObject(
         glance._Base, 'get_glance_client',
         side_effect=self.fake_get_glance_client))
     self.CONF = self.useFixture(fixture_config.Config()).conf
Esempio n. 23
0
    def test_notify_alarm_rest_action_with_ssl_verify_disable(self):
        action = 'https://host/action?ceilometer-alarm-ssl-verify=0'

        with mock.patch('eventlet.spawn_n', self._fake_spawn_n):
            with mock.patch.object(requests, 'post') as poster:
                self.service.notify_alarm(context.get_admin_context(),
                                          self._notification(action))
                poster.assert_called_with(action, data=DATA_JSON,
                                          verify=False)
Esempio n. 24
0
def notify(context, message):
    """Sends a notification as a meter using Ceilometer pipelines."""
    if not _notification_manager:
        _load_notification_manager()
    if not _pipeline_manager:
        _load_pipeline_manager()
    _notification_manager.map(
        _process_notification_for_ext, context=context or req_context.get_admin_context(), notification=message
    )
Esempio n. 25
0
 def test_notify_alarm_log_action(self):
     self.service.notify_alarm(
         context.get_admin_context(), {
             'actions': ['log://'],
             'alarm_id': 'foobar',
             'condition': {
                 'threshold': 42
             },
         })
Esempio n. 26
0
def notify(context, message):
    """Sends a notification as a meter using Ceilometer pipelines."""
    if not _pipeline_manager:
        _load_pipeline_manager()
    if not _notification_manager:
        _load_notification_manager()
    _notification_manager.map_method(
        'to_samples_and_publish',
        context=context or req_context.get_admin_context(),
        notification=message)
Esempio n. 27
0
def notify(context, message):
    """Sends a notification as a meter using Ceilometer pipelines."""
    if not _pipeline_manager:
        _load_pipeline_manager()
    if not _notification_manager:
        _load_notification_manager()
    _notification_manager.map_method('to_samples_and_publish',
                                     context=context
                                     or req_context.get_admin_context(),
                                     notification=message)
Esempio n. 28
0
    def process_request(self, request):
        request.environ['HTTP_X_SERVICE_NAME'] = \
            self.service_name or request.host
        payload = {
            'request': self.environ_to_dict(request.environ),
        }

        api.notify(context.get_admin_context(),
                   api.publisher_id(os.path.basename(sys.argv[0])),
                   'http.request', api.INFO, payload)
Esempio n. 29
0
    def test_notify_alarm_rest_action_with_ssl_verify_enable_by_user(self):
        action = 'https://host/action?ceilometer-alarm-ssl-verify=1'

        cfg.CONF.set_override("rest_notifier_ssl_verify", False, group='alarm')

        with mock.patch('eventlet.spawn_n', self._fake_spawn_n):
            with mock.patch.object(requests, 'post') as poster:
                self.service.notify_alarm(context.get_admin_context(),
                                          self._notification(action))
                poster.assert_called_with(action, data=DATA_JSON, verify=True)
Esempio n. 30
0
def notify(context, message):
    """Sends a notification as a meter using Ceilometer pipelines."""
    if not _notification_manager:
        _load_notification_manager()
    if not _pipeline_manager:
        _load_pipeline_manager()
    _notification_manager.map(_process_notification_for_ext,
                              context=context
                              or req_context.get_admin_context(),
                              notification=message)
Esempio n. 31
0
 def test_notify_alarm_invalid_action(self):
     LOG = mock.MagicMock()
     with mock.patch('ceilometer.alarm.service.LOG', LOG):
         self.service.notify_alarm(
             context.get_admin_context(),
             {
                 'actions': ['no-such-action-i-am-sure://'],
                 'alarm_id': 'foobar',
                 'condition': {'threshold': 42},
             })
         self.assertTrue(LOG.error.called)
Esempio n. 32
0
def send_sample():
    cfg.CONF.register_cli_opts([
        cfg.StrOpt('sample-name', short='n', help='Meter name.',
                   required=True),
        cfg.StrOpt('sample-type',
                   short='y',
                   help='Meter type (gauge, delta, cumulative).',
                   default='gauge',
                   required=True),
        cfg.StrOpt('sample-unit', short='U', help='Meter unit.', default=None),
        cfg.IntOpt('sample-volume',
                   short='l',
                   help='Meter volume value.',
                   default=1),
        cfg.StrOpt('sample-resource',
                   short='r',
                   help='Meter resource id.',
                   required=True),
        cfg.StrOpt('sample-user', short='u', help='Meter user id.'),
        cfg.StrOpt('sample-project', short='p', help='Meter project id.'),
        cfg.StrOpt('sample-timestamp',
                   short='i',
                   help='Meter timestamp.',
                   default=timeutils.utcnow().isoformat()),
        cfg.StrOpt('sample-metadata', short='m', help='Meter metadata.'),
    ])

    service.prepare_service()

    # Set up logging to use the console
    console = logging.StreamHandler(sys.stderr)
    console.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(message)s')
    console.setFormatter(formatter)
    root_logger = logging.getLogger('')
    root_logger.addHandler(console)
    root_logger.setLevel(logging.DEBUG)

    pipeline_manager = pipeline.setup_pipeline(
        transformer.TransformerExtensionManager('ceilometer.transformer', ), )

    with pipeline_manager.publisher(context.get_admin_context()) as p:
        p([
            sample.Sample(name=cfg.CONF.sample_name,
                          type=cfg.CONF.sample_type,
                          unit=cfg.CONF.sample_unit,
                          volume=cfg.CONF.sample_volume,
                          user_id=cfg.CONF.sample_user,
                          project_id=cfg.CONF.sample_project,
                          resource_id=cfg.CONF.sample_resource,
                          timestamp=cfg.CONF.sample_timestamp,
                          resource_metadata=cfg.CONF.sample_metadata
                          and eval(cfg.CONF.sample_metadata))
        ])
Esempio n. 33
0
 def setUp(self):
     super(TestFloatingIPPollster, self).setUp()
     self.addCleanup(mock.patch.stopall)
     self.context = context.get_admin_context()
     self.manager = manager.AgentManager()
     self.pollster = floatingip.FloatingIPPollster()
     fake_ips = self.fake_get_ips()
     patch_virt = mock.patch('ceilometer.nova_client.Client.'
                             'floating_ip_get_all',
                             return_value=fake_ips)
     patch_virt.start()
Esempio n. 34
0
    def _process_notification_for_ext(self, ext, notification):
        """Wrapper for calling pipelines when a notification arrives

        When a message is received by process_notification(), it calls
        this method with each notification plugin to allow all the
        plugins process the notification.

        """
        with self.pipeline_manager.publisher(context.get_admin_context()) as p:
            # FIXME(dhellmann): Spawn green thread?
            p(list(ext.obj.to_samples(notification)))
Esempio n. 35
0
 def test_notify_alarm_invalid_action(self):
     LOG = mock.MagicMock()
     with mock.patch('ceilometer.alarm.service.LOG', LOG):
         self.service.notify_alarm(
             context.get_admin_context(),
             {
                 'actions': ['no-such-action-i-am-sure://'],
                 'alarm_id': 'foobar',
                 'condition': {'threshold': 42},
             })
         self.assertTrue(LOG.error.called)
Esempio n. 36
0
 def setUp(self):
     super(TestFloatingIPPollster, self).setUp()
     self.addCleanup(mock.patch.stopall)
     self.context = context.get_admin_context()
     self.manager = manager.AgentManager()
     self.pollster = floatingip.FloatingIPPollster()
     fake_ips = self.fake_get_ips()
     patch_virt = mock.patch('ceilometer.nova_client.Client.'
                             'floating_ip_get_all',
                             return_value=fake_ips)
     patch_virt.start()
Esempio n. 37
0
    def _process_notification_for_ext(self, ext, notification):
        """Wrapper for calling pipelines when a notification arrives

        When a message is received by process_notification(), it calls
        this method with each notification plugin to allow all the
        plugins process the notification.

        """
        with self.pipeline_manager.publisher(context.get_admin_context()) as p:
            # FIXME(dhellmann): Spawn green thread?
            p(list(ext.obj.to_samples(notification)))
Esempio n. 38
0
    def test_notify_alarm_rest_action_with_ssl_verify_enable_by_user(self):
        action = 'https://host/action?ceilometer-alarm-ssl-verify=1'

        self.CONF.set_override("rest_notifier_ssl_verify", False,
                               group='alarm')

        with mock.patch('eventlet.spawn_n', self._fake_spawn_n):
            with mock.patch.object(requests, 'post') as poster:
                self.service.notify_alarm(context.get_admin_context(),
                                          self._notification(action))
                poster.assert_called_with(action, data=DATA_JSON,
                                          verify=True)
Esempio n. 39
0
    def process_request(self, request):
        request.environ['HTTP_X_SERVICE_NAME'] = \
            self.service_name or request.host
        payload = {
            'request': self.environ_to_dict(request.environ),
        }

        api.notify(context.get_admin_context(),
                   api.publisher_id(os.path.basename(sys.argv[0])),
                   'http.request',
                   api.INFO,
                   payload)
Esempio n. 40
0
def notify(context, message):
    """Sends a notification via RPC"""
    if not context:
        context = req_context.get_admin_context()
    priority = message.get("priority", CONF.default_notification_level)
    priority = priority.lower()
    for topic in CONF.rpc_notifier2.topics:
        topic = "%s.%s" % (topic, priority)
        try:
            rpc.notify(context, topic, message, envelope=True)
        except Exception:
            LOG.exception(_("Could not send notification to %(topic)s. " "Payload=%(message)s"), locals())
 def test_notify_alarm(self):
     data = {
         'actions': ['test://'],
         'alarm': 'foobar',
         'state': 'ALARM',
         'reason': 'Everything is on fire',
     }
     self.service.notify_alarm(context.get_admin_context(), data)
     notifications = self.service.notifiers['test'].obj.notifications
     self.assertEqual(len(notifications), 1)
     self.assertEqual(notifications[0], (urlparse.urlsplit(
         data['actions'][0]), data['alarm'], data['state'], data['reason']))
Esempio n. 42
0
    def test_notify_alarm_rest_action_ok(self):
        action = 'http://host/action'

        with mock.patch('eventlet.spawn_n', self._fake_spawn_n):
            with mock.patch.object(requests.Session, 'post') as poster:
                self.service.notify_alarm(context.get_admin_context(),
                                          self._notification(action))
                poster.assert_called_with(action, data=mock.ANY,
                                          headers=mock.ANY)
                args, kwargs = poster.call_args
                self.assertEqual(self.HTTP_HEADERS, kwargs['headers'])
                self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data']))
Esempio n. 43
0
 def test_notify_alarm_invalid_url(self):
     with mock.patch('ceilometer.openstack.common.network_utils.urlsplit',
                     self._fake_urlsplit):
         LOG = mock.MagicMock()
         with mock.patch('ceilometer.alarm.service.LOG', LOG):
             self.service.notify_alarm(
                 context.get_admin_context(),
                 {
                     'actions': ['no-such-action-i-am-sure'],
                     'alarm_id': 'foobar',
                     'condition': {'threshold': 42},
                 })
             self.assertTrue(LOG.error.called)
Esempio n. 44
0
 def test_notify_alarm_invalid_url(self):
     with mock.patch('ceilometer.openstack.common.network_utils.urlsplit',
                     self._fake_urlsplit):
         LOG = mock.MagicMock()
         with mock.patch('ceilometer.alarm.service.LOG', LOG):
             self.service.notify_alarm(
                 context.get_admin_context(),
                 {
                     'actions': ['no-such-action-i-am-sure'],
                     'alarm_id': 'foobar',
                     'condition': {'threshold': 42},
                 })
             self.assertTrue(LOG.error.called)
Esempio n. 45
0
    def test_notify_alarm_rest_action_ok(self):
        action = 'http://host/action'

        with mock.patch('eventlet.spawn_n', self._fake_spawn_n):
            with mock.patch.object(requests.Session, 'post') as poster:
                self.service.notify_alarm(context.get_admin_context(),
                                          self._notification(action))
                poster.assert_called_with(action,
                                          data=mock.ANY,
                                          headers=mock.ANY)
                args, kwargs = poster.call_args
                self.assertEqual(self.HTTP_HEADERS, kwargs['headers'])
                self.assertEqual(DATA_JSON, anyjson.loads(kwargs['data']))
Esempio n. 46
0
    def test_notify_alarm_rest_action_with_ssl_client_cert(self):
        action = 'https://host/action'
        certificate = "/etc/ssl/cert/whatever.pem"

        self.CONF.set_override("rest_notifier_certificate_file", certificate,
                               group='alarm')

        with mock.patch('eventlet.spawn_n', self._fake_spawn_n):
            with mock.patch.object(requests, 'post') as poster:
                self.service.notify_alarm(context.get_admin_context(),
                                          self._notification(action))
                poster.assert_called_with(action, data=DATA_JSON,
                                          cert=certificate, verify=True)
Esempio n. 47
0
    def test_notify_alarm_rest_action_with_ssl_verify_disable(self):
        action = 'https://host/action?ceilometer-alarm-ssl-verify=0'

        with mock.patch('eventlet.spawn_n', self._fake_spawn_n):
            with mock.patch.object(requests.Session, 'post') as poster:
                self.service.notify_alarm(context.get_admin_context(),
                                          self._notification(action))
                poster.assert_called_with(action, data=mock.ANY,
                                          headers=mock.ANY,
                                          verify=False)
                args, kwargs = poster.call_args
                self.assertEqual(self.HTTP_HEADERS, kwargs['headers'])
                self.assertEqual(DATA_JSON, jsonutils.loads(kwargs['data']))
Esempio n. 48
0
def notify(context, message):
    """Sends a notification to the RabbitMQ"""
    if not context:
        context = req_context.get_admin_context()
    priority = message.get('priority',
                           CONF.default_notification_level)
    priority = priority.lower()
    for topic in CONF.notification_topics:
        topic = '%s.%s' % (topic, priority)
        try:
            rpc.notify(context, topic, message)
        except Exception, e:
            LOG.exception(_("Could not send notification to %(topic)s. "
                            "Payload=%(message)s"), locals())
Esempio n. 49
0
def notify(context, message):
    """Sends a notification via RPC."""
    if not context:
        context = req_context.get_admin_context()
    priority = message.get('priority', CONF.default_notification_level)
    priority = priority.lower()
    for topic in CONF.rpc_notifier2.topics:
        topic = '%s.%s' % (topic, priority)
        try:
            rpc.notify(context, topic, message, envelope=True)
        except Exception:
            LOG.exception(
                _("Could not send notification to %(topic)s. "
                  "Payload=%(message)s"), locals())
Esempio n. 50
0
 def setUp(self):
     super(TestFloatingIPPollster, self).setUp()
     self.addCleanup(mock.patch.stopall)
     self.context = context.get_admin_context()
     self.manager = manager.AgentManager()
     self.manager.keystone = mock.Mock()
     self.manager.keystone.service_catalog.get_endpoints = mock.Mock(
         return_value={'network': mock.ANY})
     self.pollster = floatingip.FloatingIPPollster()
     fake_ips = self.fake_get_ips()
     patch_virt = mock.patch('ceilometer.nova_client.Client.'
                             'floating_ip_get_all',
                             return_value=fake_ips)
     patch_virt.start()
Esempio n. 51
0
    def test_notify_alarm_rest_action_with_ssl_verify_disable(self):
        action = 'https://host/action?ceilometer-alarm-ssl-verify=0'

        with mock.patch('eventlet.spawn_n', self._fake_spawn_n):
            with mock.patch.object(requests.Session, 'post') as poster:
                self.service.notify_alarm(context.get_admin_context(),
                                          self._notification(action))
                poster.assert_called_with(action,
                                          data=mock.ANY,
                                          headers=mock.ANY,
                                          verify=False)
                args, kwargs = poster.call_args
                self.assertEqual(self.HTTP_HEADERS, kwargs['headers'])
                self.assertEqual(DATA_JSON, jsonutils.loads(kwargs['data']))
Esempio n. 52
0
 def setUp(self):
     super(TestFloatingIPPollster, self).setUp()
     self.addCleanup(mock.patch.stopall)
     self.context = context.get_admin_context()
     self.manager = manager.AgentManager()
     self.manager.keystone = mock.Mock()
     self.manager.keystone.service_catalog.get_endpoints = mock.Mock(
         return_value={'network': mock.ANY})
     self.pollster = floatingip.FloatingIPPollster()
     fake_ips = self.fake_get_ips()
     patch_virt = mock.patch('ceilometer.nova_client.Client.'
                             'floating_ip_get_all',
                             return_value=fake_ips)
     patch_virt.start()
Esempio n. 53
0
def notify(context, message):
    """Sends a notification via RPC."""
    if not context:
        context = req_context.get_admin_context()
    priority = message.get('priority',
                           CONF.default_notification_level)
    priority = priority.lower()
    for topic in CONF.notification_topics:
        topic = '%s.%s' % (topic, priority)
        try:
            rpc.notify(context, topic, message)
        except Exception:
            LOG.exception(_LE("Could not send notification to %(topic)s. "
                              "Payload=%(message)s"),
                          {"topic": topic, "message": message})
Esempio n. 54
0
    def info(self, ctxt, publisher_id, event_type, payload, metadata):
        """RPC endpoint for notification messages

        When another service sends a notification over the message
        bus, this method receives it.

        :param ctxt: oslo.messaging context
        :param publisher_id: publisher of the notification
        :param event_type: type of notification
        :param payload: notification payload
        :param metadata: metadata about the notification

        """
        notification = messaging.convert_to_old_notification_format(
            'info', ctxt, publisher_id, event_type, payload, metadata)
        self.to_samples_and_publish(context.get_admin_context(), notification)
Esempio n. 55
0
    def start(self):
        super(NotificationService, self).start()
        self.pipeline_manager = pipeline.setup_pipeline()

        transport = messaging.get_transport()
        self.partition_coordinator = coordination.PartitionCoordinator()
        self.partition_coordinator.start()

        if cfg.CONF.notification.workload_partitioning:
            transporter = []
            for pipe in self.pipeline_manager.pipelines:
                transporter.append(oslo.messaging.Notifier(
                    transport,
                    driver=cfg.CONF.publisher_notifier.metering_driver,
                    publisher_id='ceilometer.notification',
                    topic='%s-%s' % (self.NOTIFICATION_IPC, pipe.name)))

            self.ctxt = context.get_admin_context()
            self.group_id = self.NOTIFICATION_NAMESPACE
        else:
            # FIXME(sileht): endpoint use notification_topics option
            # and it should not because this is oslo.messaging option
            # not a ceilometer, until we have a something to get
            # the notification_topics in an other way
            # we must create a transport to ensure the option have
            # beeen registered by oslo.messaging
            messaging.get_notifier(transport, '')
            transporter = self.pipeline_manager
            self.group_id = None

        self.listeners = self.pipeline_listeners = []
        self._configure_main_queue_listeners(transporter)

        if cfg.CONF.notification.workload_partitioning:
            self.partition_coordinator.join_group(self.group_id)
            self._configure_pipeline_listeners()
            self.partition_coordinator.watch_group(self.group_id,
                                                   self._refresh_agent)

            self.tg.add_timer(cfg.CONF.coordination.heartbeat,
                              self.partition_coordinator.heartbeat)
            self.tg.add_timer(cfg.CONF.coordination.check_watchers,
                              self.partition_coordinator.run_watchers)

        # Add a dummy thread to have wait() working
        self.tg.add_timer(604800, lambda: None)
    def test_notify_alarm_rest_action_ok(self):
        action = 'http://host/action'
        data_json = '{"reason": "what ?", "alarm": "foobar", "state": "ALARM"}'

        with mock.patch('eventlet.spawn_n', self._fake_spawn_n):
            with mock.patch.object(requests, 'post') as poster:
                self.service.notify_alarm(
                    context.get_admin_context(), {
                        'actions': [action],
                        'alarm': 'foobar',
                        'condition': {
                            'threshold': 42
                        },
                        'reason': 'what ?',
                        'state': 'ALARM',
                    })
                poster.assert_called_with(action, data=data_json)
Esempio n. 57
0
 def test_notify_alarm(self):
     data = {
         'actions': ['test://'],
         'alarm_id': 'foobar',
         'previous': 'OK',
         'current': 'ALARM',
         'reason': 'Everything is on fire',
         'reason_data': {
             'fire': 'everywhere'
         }
     }
     self.service.notify_alarm(context.get_admin_context(), data)
     notifications = self.service.notifiers['test'].obj.notifications
     self.assertEqual(len(notifications), 1)
     self.assertEqual(notifications[0],
                      (urlparse.urlsplit(data['actions'][0]),
                       data['alarm_id'], data['previous'], data['current'],
                       data['reason'], data['reason_data']))