Ejemplo n.º 1
0
def _send_instance_update_notification(context, instance, old_vm_state=None,
            old_task_state=None, new_vm_state=None, new_task_state=None,
            service="compute", host=None, old_display_name=None):
    """Send 'compute.instance.update' notification to inform observers
    about instance state changes.
    """

    payload = info_from_instance(context, instance, None, None)

    # determine how we'll report states
    payload.update(
        _compute_states_payload(
            instance, old_vm_state, old_task_state,
            new_vm_state, new_task_state))

    # add audit fields:
    (audit_start, audit_end) = audit_period_bounds(current_period=True)
    payload["audit_period_beginning"] = audit_start
    payload["audit_period_ending"] = audit_end

    # add bw usage info:
    bw = bandwidth_usage(instance, audit_start)
    payload["bandwidth"] = bw

    # add old display name if it is changed
    if old_display_name:
        payload["old_display_name"] = old_display_name

    rpc.get_notifier(service, host).info(context,
                                         'compute.instance.update', payload)
Ejemplo n.º 2
0
    def test_set_vm_state_and_notify(self):
        expected_uuid = 'fake-uuid'
        request_spec = dict(instance_properties=dict(uuid='other-uuid'))
        updates = dict(vm_state='fake-vm-state')
        service = 'fake-service'
        method = 'fake-method'
        exc_info = 'exc_info'

        self.mox.StubOutWithMock(compute_utils,
                                 'add_instance_fault_from_exc')
        self.mox.StubOutWithMock(notifications, 'send_update')
        self.mox.StubOutWithMock(db, 'instance_update_and_get_original')

        self.mox.StubOutWithMock(rpc, 'get_notifier')
        notifier = self.mox.CreateMockAnything()
        rpc.get_notifier(service).AndReturn(notifier)

        old_ref = 'old_ref'
        new_ref = 'new_ref'
        inst_obj = 'inst_obj'

        db.instance_update_and_get_original(
            self.context, expected_uuid, updates,
            columns_to_join=['system_metadata']).AndReturn((old_ref, new_ref))
        notifications.send_update(self.context, old_ref, inst_obj,
                                  service=service)
        compute_utils.add_instance_fault_from_exc(
                self.context,
                inst_obj, exc_info, mox.IsA(tuple))

        payload = dict(request_spec=request_spec,
                       instance_properties=request_spec.get(
                           'instance_properties', {}),
                       instance_id=expected_uuid,
                       state='fake-vm-state',
                       method=method,
                       reason=exc_info)
        event_type = '%s.%s' % (service, method)
        notifier.error(self.context, event_type, payload)

        self.mox.ReplayAll()

        with mock.patch.object(objects.Instance, '_from_db_object',
                               return_value=inst_obj):
            scheduler_utils.set_vm_state_and_notify(self.context,
                                                    expected_uuid,
                                                    service,
                                                    method,
                                                    updates,
                                                    exc_info,
                                                    request_spec,
                                                    db)
Ejemplo n.º 3
0
def send_api_fault(url, status, exception):
    """Send an api.fault notification."""

    if not CONF.notify_api_faults:
        return

    payload = {'url': url, 'exception': six.text_type(exception),
               'status': status}

    rpc.get_notifier('api').error(common_context.get_current() or
                                  patron.context.get_admin_context(),
                                  'api.fault',
                                  payload)
Ejemplo n.º 4
0
    def test_set_vm_state_and_notify(self):
        expected_uuid = 'fake-uuid'
        request_spec = dict(instance_properties=dict(uuid='other-uuid'))
        updates = dict(vm_state='fake-vm-state')
        service = 'fake-service'
        method = 'fake-method'
        exc_info = 'exc_info'

        self.mox.StubOutWithMock(compute_utils, 'add_instance_fault_from_exc')
        self.mox.StubOutWithMock(notifications, 'send_update')
        self.mox.StubOutWithMock(db, 'instance_update_and_get_original')

        self.mox.StubOutWithMock(rpc, 'get_notifier')
        notifier = self.mox.CreateMockAnything()
        rpc.get_notifier(service).AndReturn(notifier)

        old_ref = 'old_ref'
        new_ref = 'new_ref'
        inst_obj = 'inst_obj'

        db.instance_update_and_get_original(
            self.context,
            expected_uuid,
            updates,
            columns_to_join=['system_metadata']).AndReturn((old_ref, new_ref))
        notifications.send_update(self.context,
                                  old_ref,
                                  inst_obj,
                                  service=service)
        compute_utils.add_instance_fault_from_exc(self.context, inst_obj,
                                                  exc_info, mox.IsA(tuple))

        payload = dict(request_spec=request_spec,
                       instance_properties=request_spec.get(
                           'instance_properties', {}),
                       instance_id=expected_uuid,
                       state='fake-vm-state',
                       method=method,
                       reason=exc_info)
        event_type = '%s.%s' % (service, method)
        notifier.error(self.context, event_type, payload)

        self.mox.ReplayAll()

        with mock.patch.object(objects.Instance,
                               '_from_db_object',
                               return_value=inst_obj):
            scheduler_utils.set_vm_state_and_notify(self.context,
                                                    expected_uuid, service,
                                                    method, updates, exc_info,
                                                    request_spec, db)
Ejemplo n.º 5
0
 def test_notify_usage_exists_instance_not_found(self):
     # Ensure 'exists' notification generates appropriate usage data.
     instance_id = self._create_instance()
     instance = objects.Instance.get_by_id(self.context, instance_id,
             expected_attrs=['metadata', 'system_metadata', 'info_cache'])
     self.compute.terminate_instance(self.context, instance, [], [])
     compute_utils.notify_usage_exists(
         rpc.get_notifier('compute'), self.context, instance)
     msg = fake_notifier.NOTIFICATIONS[-1]
     self.assertEqual(msg.priority, 'INFO')
     self.assertEqual(msg.event_type, 'compute.instance.exists')
     payload = msg.payload
     self.assertEqual(payload['tenant_id'], self.project_id)
     self.assertEqual(payload['user_id'], self.user_id)
     self.assertEqual(payload['instance_id'], instance['uuid'])
     self.assertEqual(payload['instance_type'], 'm1.tiny')
     type_id = flavors.get_flavor_by_name('m1.tiny')['id']
     self.assertEqual(str(payload['instance_type_id']), str(type_id))
     flavor_id = flavors.get_flavor_by_name('m1.tiny')['flavorid']
     self.assertEqual(str(payload['instance_flavor_id']), str(flavor_id))
     for attr in ('display_name', 'created_at', 'launched_at',
                  'state', 'state_description',
                  'bandwidth', 'audit_period_beginning',
                  'audit_period_ending', 'image_meta'):
         self.assertIn(attr, payload, "Key %s not in payload" % attr)
     self.assertEqual(payload['image_meta'], {})
     image_ref_url = "%s/images/1" % glance.generate_glance_url()
     self.assertEqual(payload['image_ref_url'], image_ref_url)
Ejemplo n.º 6
0
 def __init__(self, host=None, db_driver=None, service_name='undefined'):
     if not host:
         host = CONF.host
     self.host = host
     self.backdoor_port = None
     self.service_name = service_name
     self.notifier = rpc.get_notifier(self.service_name, self.host)
     self.additional_endpoints = []
     super(Manager, self).__init__(db_driver)
Ejemplo n.º 7
0
def notify_about_server_group_update(context, event_suffix, sg_payload):
    """Send a notification about server group update.

    :param event_suffix: Event type like "create.start" or "create.end"
    :param sg_payload: payload for server group update
    """
    notifier = rpc.get_notifier(service='servergroup')

    notifier.info(context, 'servergroup.%s' % event_suffix, sg_payload)
Ejemplo n.º 8
0
def notify_about_server_group_update(context, event_suffix, sg_payload):
    """Send a notification about server group update.

    :param event_suffix: Event type like "create.start" or "create.end"
    :param sg_payload: payload for server group update
    """
    notifier = rpc.get_notifier(service='servergroup')

    notifier.info(context, 'servergroup.%s' % event_suffix, sg_payload)
Ejemplo n.º 9
0
    def get_connection(self):
        """Returns a connection to the hypervisor

        This method should be used to create and return a well
        configured connection to the hypervisor.

        :returns: a libvirt.virConnect object
        """
        try:
            conn = self._get_connection()
        except libvirt.libvirtError as ex:
            LOG.exception(_LE("Connection to libvirt failed: %s"), ex)
            payload = dict(ip=CONF.my_ip,
                           method='_connect',
                           reason=ex)
            rpc.get_notifier('compute').error(patron_context.get_admin_context(),
                                              'compute.libvirt.error',
                                              payload)
            raise exception.HypervisorUnavailable(host=CONF.host)

        return conn
Ejemplo n.º 10
0
 def __init__(self):
     super(LocalManager, self).__init__()
     # NOTE(vish): setting the host to none ensures that the actual
     #             l3driver commands for l3 are done via rpc.
     self.host = None
     self.servicegroup_api = servicegroup.API()
     self.network_rpcapi = network_rpcapi.NetworkAPI()
     self.floating_dns_manager = importutils.import_object(
             CONF.floating_ip_dns_manager)
     self.instance_dns_manager = importutils.import_object(
             CONF.instance_dns_manager)
     self.notifier = rpc.get_notifier('network', CONF.host)
Ejemplo n.º 11
0
def notify_about_host_update(context, event_suffix, host_payload):
    """Send a notification about host update.

    :param event_suffix: Event type like "create.start" or "create.end"
    :param host_payload: payload for host update. It is a dict and there
                         should be at least the 'host_name' key in this
                         dict.
    """
    host_identifier = host_payload.get('host_name')
    if not host_identifier:
        LOG.warning(_LW("No host name specified for the notification of "
                        "HostAPI.%s and it will be ignored"), event_suffix)
        return

    notifier = rpc.get_notifier(service='api', host=host_identifier)

    notifier.info(context, 'HostAPI.%s' % event_suffix, host_payload)
Ejemplo n.º 12
0
def notify_about_aggregate_update(context, event_suffix, aggregate_payload):
    """Send a notification about aggregate update.

    :param event_suffix: Event type like "create.start" or "create.end"
    :param aggregate_payload: payload for aggregate update
    """
    aggregate_identifier = aggregate_payload.get('aggregate_id', None)
    if not aggregate_identifier:
        aggregate_identifier = aggregate_payload.get('name', None)
        if not aggregate_identifier:
            LOG.debug("No aggregate id or name specified for this "
                      "notification and it will be ignored")
            return

    notifier = rpc.get_notifier(service='aggregate', host=aggregate_identifier)

    notifier.info(context, 'aggregate.%s' % event_suffix, aggregate_payload)
Ejemplo n.º 13
0
def notify_about_host_update(context, event_suffix, host_payload):
    """Send a notification about host update.

    :param event_suffix: Event type like "create.start" or "create.end"
    :param host_payload: payload for host update. It is a dict and there
                         should be at least the 'host_name' key in this
                         dict.
    """
    host_identifier = host_payload.get('host_name')
    if not host_identifier:
        LOG.warning(
            _LW("No host name specified for the notification of "
                "HostAPI.%s and it will be ignored"), event_suffix)
        return

    notifier = rpc.get_notifier(service='api', host=host_identifier)

    notifier.info(context, 'HostAPI.%s' % event_suffix, host_payload)
Ejemplo n.º 14
0
def notify_about_aggregate_update(context, event_suffix, aggregate_payload):
    """Send a notification about aggregate update.

    :param event_suffix: Event type like "create.start" or "create.end"
    :param aggregate_payload: payload for aggregate update
    """
    aggregate_identifier = aggregate_payload.get('aggregate_id', None)
    if not aggregate_identifier:
        aggregate_identifier = aggregate_payload.get('name', None)
        if not aggregate_identifier:
            LOG.debug("No aggregate id or name specified for this "
                      "notification and it will be ignored")
            return

    notifier = rpc.get_notifier(service='aggregate',
                                host=aggregate_identifier)

    notifier.info(context, 'aggregate.%s' % event_suffix, aggregate_payload)
Ejemplo n.º 15
0
def set_vm_state_and_notify(context, instance_uuid, service, method, updates,
                            ex, request_spec, db):
    """changes VM state and notifies."""
    LOG.warning(_LW("Failed to %(service)s_%(method)s: %(ex)s"), {
        'service': service,
        'method': method,
        'ex': ex
    })

    vm_state = updates['vm_state']
    properties = request_spec.get('instance_properties', {})
    # NOTE(vish): We shouldn't get here unless we have a catastrophic
    #             failure, so just set the instance to its internal state
    notifier = rpc.get_notifier(service)
    state = vm_state.upper()
    LOG.warning(_LW('Setting instance to %s state.'),
                state,
                instance_uuid=instance_uuid)

    # update instance state and notify on the transition
    # NOTE(hanlind): the send_update() call below is going to want to
    # know about the flavor, so we need to join the appropriate things
    # here and objectify the results.
    (old_ref, new_ref) = db.instance_update_and_get_original(
        context, instance_uuid, updates, columns_to_join=['system_metadata'])
    inst_obj = objects.Instance._from_db_object(
        context,
        objects.Instance(),
        new_ref,
        expected_attrs=['system_metadata'])
    notifications.send_update(context, old_ref, inst_obj, service=service)
    compute_utils.add_instance_fault_from_exc(context, inst_obj, ex,
                                              sys.exc_info())

    payload = dict(request_spec=request_spec,
                   instance_properties=properties,
                   instance_id=instance_uuid,
                   state=vm_state,
                   method=method,
                   reason=ex)

    event_type = '%s.%s' % (service, method)
    notifier.error(context, event_type, payload)
Ejemplo n.º 16
0
 def _get_host_metrics(self, context, nodename):
     """Get the metrics from monitors and
     notify information to message bus.
     """
     metrics = []
     metrics_info = {}
     for monitor in self.monitors:
         try:
             metrics += monitor.get_metrics(nodename=nodename)
         except Exception:
             LOG.warning(_LW("Cannot get the metrics from %s."), monitor)
     if metrics:
         metrics_info['nodename'] = nodename
         metrics_info['metrics'] = metrics
         metrics_info['host'] = self.host
         metrics_info['host_ip'] = CONF.my_ip
         notifier = rpc.get_notifier(service='compute', host=nodename)
         notifier.info(context, 'compute.metrics.update', metrics_info)
     return metrics
Ejemplo n.º 17
0
    def wrapped_func(*args, **kwarg):
        body = {}
        body['args'] = []
        body['kwarg'] = {}
        for arg in args:
            body['args'].append(arg)
        for key in kwarg:
            body['kwarg'][key] = kwarg[key]

        ctxt = common_context.get_context_from_function_and_args(
            fn, args, kwarg)

        notifier = rpc.get_notifier('api',
                                    publisher_id=(CONF.default_publisher_id
                                                  or CONF.host))
        method = notifier.getattr(CONF.default_notification_level.lower(),
                                  'info')
        method(ctxt, name, body)

        return fn(*args, **kwarg)
Ejemplo n.º 18
0
 def test_notify_about_instance_usage(self):
     instance_id = self._create_instance()
     instance = objects.Instance.get_by_id(self.context, instance_id,
             expected_attrs=['metadata', 'system_metadata', 'info_cache'])
     # Set some system metadata
     sys_metadata = {'image_md_key1': 'val1',
                     'image_md_key2': 'val2',
                     'other_data': 'meow'}
     instance.system_metadata.update(sys_metadata)
     instance.save()
     extra_usage_info = {'image_name': 'fake_name'}
     compute_utils.notify_about_instance_usage(
         rpc.get_notifier('compute'),
         self.context, instance, 'create.start',
         extra_usage_info=extra_usage_info)
     self.assertEqual(len(fake_notifier.NOTIFICATIONS), 1)
     msg = fake_notifier.NOTIFICATIONS[0]
     self.assertEqual(msg.priority, 'INFO')
     self.assertEqual(msg.event_type, 'compute.instance.create.start')
     payload = msg.payload
     self.assertEqual(payload['tenant_id'], self.project_id)
     self.assertEqual(payload['user_id'], self.user_id)
     self.assertEqual(payload['instance_id'], instance['uuid'])
     self.assertEqual(payload['instance_type'], 'm1.tiny')
     type_id = flavors.get_flavor_by_name('m1.tiny')['id']
     self.assertEqual(str(payload['instance_type_id']), str(type_id))
     flavor_id = flavors.get_flavor_by_name('m1.tiny')['flavorid']
     self.assertEqual(str(payload['instance_flavor_id']), str(flavor_id))
     for attr in ('display_name', 'created_at', 'launched_at',
                  'state', 'state_description', 'image_meta'):
         self.assertIn(attr, payload, "Key %s not in payload" % attr)
     self.assertEqual(payload['image_meta'],
             {'md_key1': 'val1', 'md_key2': 'val2'})
     self.assertEqual(payload['image_name'], 'fake_name')
     image_ref_url = "%s/images/1" % glance.generate_glance_url()
     self.assertEqual(payload['image_ref_url'], image_ref_url)
     self.compute.terminate_instance(self.context, instance, [], [])
Ejemplo n.º 19
0
 def __init__(self, *args, **kwargs):
     super(FilterScheduler, self).__init__(*args, **kwargs)
     self.options = scheduler_options.SchedulerOptions()
     self.notifier = rpc.get_notifier('scheduler')