Ejemplo n.º 1
0
def fake_instance_obj(context, obj_instance_class=None, **updates):
    if obj_instance_class is None:
        obj_instance_class = objects.Instance
    expected_attrs = updates.pop('expected_attrs', None)
    flavor = updates.pop('flavor', None)
    if not flavor:
        flavor = objects.Flavor(id=1,
                                name='flavor1',
                                memory_mb=256,
                                vcpus=1,
                                root_gb=1,
                                ephemeral_gb=1,
                                flavorid='1',
                                swap=0,
                                rxtx_factor=1.0,
                                vcpu_weight=1,
                                disabled=False,
                                is_public=True,
                                extra_specs={},
                                projects=[])
        flavor.obj_reset_changes()
    inst = obj_instance_class._from_db_object(context,
                                              obj_instance_class(),
                                              fake_db_instance(**updates),
                                              expected_attrs=expected_attrs)
    inst.keypairs = objects.KeyPairList(objects=[])
    if flavor:
        inst.flavor = flavor
    inst.old_flavor = None
    inst.new_flavor = None
    inst.obj_reset_changes()
    return inst
Ejemplo n.º 2
0
def fake_instance_obj(context, obj_instance_class=None, **updates):
    if obj_instance_class is None:
        obj_instance_class = objects.Instance
    expected_attrs = updates.pop('expected_attrs', None)
    flavor = updates.pop('flavor', None)
    if not flavor:
        flavor = objects.Flavor(id=1, name='flavor1',
                                memory_mb=256, vcpus=1,
                                root_gb=1, ephemeral_gb=1,
                                flavorid='1',
                                swap=0, rxtx_factor=1.0,
                                vcpu_weight=1,
                                disabled=False,
                                is_public=True,
                                extra_specs={},
                                projects=[])
        flavor.obj_reset_changes()
    inst = obj_instance_class._from_db_object(context,
               obj_instance_class(), fake_db_instance(**updates),
               expected_attrs=expected_attrs)
    inst.keypairs = objects.KeyPairList(objects=[])
    inst.tags = objects.TagList()
    if flavor:
        inst.flavor = flavor
        # This is needed for instance quota counting until we have the
        # ability to count allocations in placement.
        if 'vcpus' in flavor and 'vcpus' not in updates:
            inst.vcpus = flavor.vcpus
        if 'memory_mb' in flavor and 'memory_mb' not in updates:
            inst.memory_mb = flavor.memory_mb
    inst.old_flavor = None
    inst.new_flavor = None
    inst.obj_reset_changes()
    return inst
Ejemplo n.º 3
0
    def test_notify_about_instance_create(self):
        keypair = objects.KeyPair(name='my-key',
                                  user_id='fake',
                                  type='ssh',
                                  public_key=self.public_key,
                                  fingerprint=self.fingerprint)
        keypairs = objects.KeyPairList(objects=[keypair])
        instance = create_instance(self.context, params={'keypairs': keypairs})

        compute_utils.notify_about_instance_create(self.context,
                                                   instance,
                                                   host='fake-compute',
                                                   phase='start')

        self.assertEqual(1, len(fake_notifier.VERSIONED_NOTIFICATIONS))
        notification = fake_notifier.VERSIONED_NOTIFICATIONS[0]

        self.assertEqual('INFO', notification['priority'])
        self.assertEqual('instance.create.start', notification['event_type'])
        self.assertEqual('nova-compute:fake-compute',
                         notification['publisher_id'])

        payload = notification['payload']['nova_object.data']
        self.assertEqual('fake', payload['tenant_id'])
        self.assertEqual('fake', payload['user_id'])
        self.assertEqual(instance['uuid'], payload['uuid'])

        flavorid = flavors.get_flavor_by_name('m1.tiny')['flavorid']
        flavor = payload['flavor']['nova_object.data']
        self.assertEqual(flavorid, str(flavor['flavorid']))

        keypairs_payload = payload['keypairs']
        self.assertEqual(1, len(keypairs_payload))
        keypair_data = keypairs_payload[0]['nova_object.data']
        self.assertEqual(
            keypair_data, {
                'name': 'my-key',
                'user_id': 'fake',
                'type': 'ssh',
                'public_key': self.public_key,
                'fingerprint': self.fingerprint
            })

        for attr in ('display_name', 'created_at', 'launched_at', 'state',
                     'task_state', 'display_description', 'locked',
                     'auto_disk_config'):
            self.assertIn(attr, payload, "Key %s not in payload" % attr)

        self.assertEqual(uuids.fake_image_ref, payload['image_uuid'])
Ejemplo n.º 4
0
    def _create_instance_data(self):
        """Creates an instance record and associated data like BDMs, VIFs,
        migrations, etc in the source cell and returns the Instance object.

        The idea is to create as many things from the
        Instance.INSTANCE_OPTIONAL_ATTRS list as possible.

        :returns: The created Instance and Migration objects
        """
        # Create the nova-compute services record first.
        fake_service = test_service._fake_service()
        fake_service.pop('version', None)  # version field is immutable
        fake_service.pop('id', None)  # cannot create with an id set
        service = objects.Service(self.source_context, **fake_service)
        service.create()
        # Create the compute node using the service.
        fake_compute_node = copy.copy(test_compute_node.fake_compute_node)
        fake_compute_node['host'] = service.host
        fake_compute_node['hypervisor_hostname'] = service.host
        fake_compute_node['stats'] = {}  # the object requires a dict
        fake_compute_node['service_id'] = service.id
        fake_compute_node.pop('id', None)  # cannot create with an id set
        compute_node = objects.ComputeNode(self.source_context,
                                           **fake_compute_node)
        compute_node.create()

        # Build an Instance object with basic fields set.
        updates = {
            'metadata': {
                'foo': 'bar'
            },
            'system_metadata': {
                'roles': ['member']
            },
            'host': compute_node.host,
            'node': compute_node.hypervisor_hostname
        }
        inst = fake_instance.fake_instance_obj(self.source_context, **updates)
        delattr(inst, 'id')  # cannot create an instance with an id set
        # Now we have to dirty all of the fields because fake_instance_obj
        # uses Instance._from_db_object to create the Instance object we have
        # but _from_db_object calls obj_reset_changes() which resets all of
        # the fields that were on the object, including the basic stuff like
        # the 'host' field, which means those fields don't get set in the DB.
        # TODO(mriedem): This should live in fake_instance_obj with a
        # make_creatable kwarg.
        for field in inst.obj_fields:
            if field in inst:
                setattr(inst, field, getattr(inst, field))
        # Make sure at least one expected basic field is dirty on the Instance.
        self.assertIn('host', inst.obj_what_changed())
        # Set the optional fields on the instance before creating it.
        inst.pci_requests = objects.InstancePCIRequests(requests=[
            objects.InstancePCIRequest(
                **test_instance_pci_requests.fake_pci_requests[0])
        ])
        inst.numa_topology = objects.InstanceNUMATopology(
            cells=test_instance_numa.fake_obj_numa_topology.cells)
        inst.trusted_certs = objects.TrustedCerts(ids=[uuids.cert])
        inst.vcpu_model = test_vcpu_model.fake_vcpumodel
        inst.keypairs = objects.KeyPairList(
            objects=[objects.KeyPair(**test_keypair.fake_keypair)])
        inst.device_metadata = (
            test_instance_device_metadata.get_fake_obj_device_metadata(
                self.source_context))
        # FIXME(mriedem): db.instance_create does not handle tags
        inst.obj_reset_changes(['tags'])
        inst.create()

        bdm = {
            'instance_uuid': inst.uuid,
            'source_type': 'volume',
            'destination_type': 'volume',
            'volume_id': uuids.volume_id,
            'volume_size': 1,
            'device_name': '/dev/vda',
        }
        bdm = objects.BlockDeviceMapping(
            self.source_context,
            **fake_block_device.FakeDbBlockDeviceDict(bdm_dict=bdm))
        delattr(bdm, 'id')  # cannot create a bdm with an id set
        bdm.obj_reset_changes(['id'])
        bdm.create()

        vif = objects.VirtualInterface(self.source_context,
                                       address='de:ad:be:ef:ca:fe',
                                       uuid=uuids.port,
                                       instance_uuid=inst.uuid)
        vif.create()

        info_cache = objects.InstanceInfoCache().new(self.source_context,
                                                     inst.uuid)
        info_cache.network_info = network_model.NetworkInfo(
            [network_model.VIF(id=vif.uuid, address=vif.address)])
        info_cache.save(update_cells=False)

        objects.TagList.create(self.source_context, inst.uuid, ['test'])

        try:
            raise test.TestingException('test-fault')
        except test.TestingException as fault:
            compute_utils.add_instance_fault_from_exc(self.source_context,
                                                      inst, fault)

        objects.InstanceAction().action_start(self.source_context,
                                              inst.uuid,
                                              'resize',
                                              want_result=False)
        objects.InstanceActionEvent().event_start(self.source_context,
                                                  inst.uuid,
                                                  'migrate_server',
                                                  want_result=False)

        # Create a fake migration for the cross-cell resize operation.
        migration = objects.Migration(
            self.source_context,
            **test_migration.fake_db_migration(instance_uuid=inst.uuid,
                                               cross_cell_move=True,
                                               migration_type='resize'))
        delattr(migration, 'id')  # cannot create a migration with an id set
        migration.obj_reset_changes(['id'])
        migration.create()

        # Create an old non-resize migration to make sure it is copied to the
        # target cell database properly.
        old_migration = objects.Migration(
            self.source_context,
            **test_migration.fake_db_migration(instance_uuid=inst.uuid,
                                               migration_type='live-migration',
                                               status='completed',
                                               uuid=uuids.old_migration))
        delattr(old_migration, 'id')  # cannot create a migration with an id
        old_migration.obj_reset_changes(['id'])
        old_migration.create()

        fake_pci_device = copy.copy(test_pci_device.fake_db_dev)
        fake_pci_device['extra_info'] = {}  # the object requires a dict
        fake_pci_device['compute_node_id'] = compute_node.id
        pci_device = objects.PciDevice.create(self.source_context,
                                              fake_pci_device)
        pci_device.allocate(inst)  # sets the status and instance_uuid fields
        pci_device.save()

        # Return a fresh copy of the instance from the DB with as many joined
        # fields loaded as possible.
        expected_attrs = copy.copy(instance_obj.INSTANCE_OPTIONAL_ATTRS)
        # Cannot load fault from get_by_uuid.
        expected_attrs.remove('fault')
        inst = objects.Instance.get_by_uuid(self.source_context,
                                            inst.uuid,
                                            expected_attrs=expected_attrs)
        return inst, migration