Ejemplo n.º 1
0
    def setUp(self):
        super(SimpleTenantUsageControllerTest, self).setUp()
        self.controller = simple_tenant_usage.SimpleTenantUsageController()

        class FakeComputeAPI:
            def get_instance_type(self, context, flavor_type):
                if flavor_type == 1:
                    return instance_types.get_default_instance_type()
                else:
                    raise exception.InstanceTypeNotFound(flavor_type)

        self.compute_api = FakeComputeAPI()
        self.context = None

        now = datetime.datetime.now()
        self.baseinst = dict(display_name='foo',
                             launched_at=now - datetime.timedelta(1),
                             terminated_at=now,
                             instance_type_id=1,
                             vm_state='deleted',
                             deleted=0)
        basetype = instance_types.get_default_instance_type()
        sys_meta = utils.dict_to_metadata(
            instance_types.save_instance_type_info({}, basetype))
        self.baseinst['system_metadata'] = sys_meta
        self.basetype = instance_types.extract_instance_type(self.baseinst)
Ejemplo n.º 2
0
 def test_delete_instance_type_info(self):
     instance_type = instance_types.get_default_instance_type()
     metadata = {}
     instance_types.save_instance_type_info(metadata, instance_type)
     instance_types.save_instance_type_info(metadata, instance_type, '_')
     instance_types.delete_instance_type_info(metadata, '', '_')
     self.assertEqual(metadata, {})
    def setUp(self):
        super(SimpleTenantUsageControllerTest, self).setUp()
        self.controller = simple_tenant_usage.SimpleTenantUsageController()

        class FakeComputeAPI:
            def get_instance_type(self, context, flavor_type):
                if flavor_type == 1:
                    return instance_types.get_default_instance_type()
                else:
                    raise exception.InstanceTypeNotFound(flavor_type)

        self.compute_api = FakeComputeAPI()
        self.context = None

        now = datetime.datetime.now()
        self.baseinst = dict(display_name='foo',
                             launched_at=now - datetime.timedelta(1),
                             terminated_at=now,
                             instance_type_id=1,
                             vm_state='deleted',
                             deleted=0)
        basetype = instance_types.get_default_instance_type()
        sys_meta = utils.dict_to_metadata(
            instance_types.save_instance_type_info({}, basetype))
        self.baseinst['system_metadata'] = sys_meta
        self.basetype = instance_types.extract_instance_type(self.baseinst)
Ejemplo n.º 4
0
 def test_get_flavor_from_deleted_with_id(self):
     # Deleted instances may not have type info in system_metadata,
     # so verify that they get their type from a lookup of their
     # instance_type_id
     inst_without_sys_meta = dict(self.baseinst, system_metadata=[],
                                  deleted=1)
     flavor = self.controller._get_flavor(self.context, self.compute_api,
                                          inst_without_sys_meta, {})
     self.assertEqual(flavor, instance_types.get_default_instance_type())
Ejemplo n.º 5
0
 def test_create_instance_defaults_display_name(self):
     """Verify that an instance cannot be created without a display_name."""
     cases = [dict(), dict(display_name=None)]
     for instance in cases:
         ref = self.compute_api.create(self.context,
             instance_types.get_default_instance_type(), None, **instance)
         try:
             self.assertNotEqual(ref[0]['display_name'], None)
         finally:
             db.instance_destroy(self.context, ref[0]['id'])
 def test_get_flavor_from_deleted_with_id(self):
     # Deleted instances may not have type info in system_metadata,
     # so verify that they get their type from a lookup of their
     # instance_type_id
     inst_without_sys_meta = dict(self.baseinst,
                                  system_metadata=[],
                                  deleted=1)
     flavor = self.controller._get_flavor(self.context, self.compute_api,
                                          inst_without_sys_meta, {})
     self.assertEqual(flavor, instance_types.get_default_instance_type())
Ejemplo n.º 7
0
 def test_default_hostname_generator(self):
     cases = [(None, 'server_1'), ('Hello, Server!', 'hello_server'),
              ('<}\x1fh\x10e\x08l\x02l\x05o\x12!{>', 'hello')]
     for display_name, hostname in cases:
         ref = self.compute_api.create(self.context,
             instance_types.get_default_instance_type(), None,
             display_name=display_name)
         try:
             self.assertEqual(ref[0]['hostname'], hostname)
         finally:
             db.instance_destroy(self.context, ref[0]['id'])
Ejemplo n.º 8
0
 def test_create_instance_defaults_display_name(self):
     """Verify that an instance cannot be created without a display_name."""
     cases = [dict(), dict(display_name=None)]
     for instance in cases:
         ref = self.compute_api.create(
             self.context, instance_types.get_default_instance_type(), None,
             **instance)
         try:
             self.assertNotEqual(ref[0]['display_name'], None)
         finally:
             db.instance_destroy(self.context, ref[0]['id'])
Ejemplo n.º 9
0
 def test_default_hostname_generator(self):
     cases = [(None, 'server_1'), ('Hello, Server!', 'hello_server'),
              ('<}\x1fh\x10e\x08l\x02l\x05o\x12!{>', 'hello')]
     for display_name, hostname in cases:
         ref = self.compute_api.create(
             self.context,
             instance_types.get_default_instance_type(),
             None,
             display_name=display_name)
         try:
             self.assertEqual(ref[0]['hostname'], hostname)
         finally:
             db.instance_destroy(self.context, ref[0]['id'])
Ejemplo n.º 10
0
    def _test_extract_instance_type(self, prefix):
        instance_type = instance_types.get_default_instance_type()

        metadata = {}
        instance_types.save_instance_type_info(metadata, instance_type, prefix)
        instance = {'system_metadata': self._dict_to_metadata(metadata)}
        _instance_type = instance_types.extract_instance_type(instance, prefix)

        props = instance_types.system_metadata_instance_type_props.keys()
        for key in instance_type.keys():
            if key not in props:
                del instance_type[key]

        self.assertEqual(instance_type, _instance_type)
    def _test_extract_instance_type(self, prefix):
        instance_type = instance_types.get_default_instance_type()

        metadata = {}
        instance_types.save_instance_type_info(metadata, instance_type, prefix)
        instance = {"system_metadata": self._dict_to_metadata(metadata)}
        _instance_type = instance_types.extract_instance_type(instance, prefix)

        props = instance_types.system_metadata_instance_type_props.keys()
        for key in instance_type.keys():
            if key not in props:
                del instance_type[key]

        self.assertEqual(instance_type, _instance_type)
Ejemplo n.º 12
0
    def test_destroy_instance_disassociates_security_groups(self):
        """Make sure destroying disassociates security groups"""
        group = self._create_group()

        ref = self.compute_api.create(
                self.context,
                instance_type=instance_types.get_default_instance_type(),
                image_href=None,
                security_group=['testgroup'])
        try:
            db.instance_destroy(self.context, ref[0]['id'])
            group = db.security_group_get(self.context, group['id'])
            self.assert_(len(group.instances) == 0)
        finally:
            db.security_group_destroy(self.context, group['id'])
Ejemplo n.º 13
0
    def test_destroy_instance_disassociates_security_groups(self):
        """Make sure destroying disassociates security groups"""
        group = self._create_group()

        ref = self.compute_api.create(
            self.context,
            instance_type=instance_types.get_default_instance_type(),
            image_href=None,
            security_group=['testgroup'])
        try:
            db.instance_destroy(self.context, ref[0]['id'])
            group = db.security_group_get(self.context, group['id'])
            self.assert_(len(group.instances) == 0)
        finally:
            db.security_group_destroy(self.context, group['id'])
Ejemplo n.º 14
0
    def test_save_instance_type_info(self):
        instance_type = instance_types.get_default_instance_type()

        example = {}
        example_prefix = {}

        for key in instance_types.system_metadata_instance_type_props.keys():
            example['instance_type_%s' % key] = instance_type[key]
            example_prefix['fooinstance_type_%s' % key] = instance_type[key]

        metadata = {}
        instance_types.save_instance_type_info(metadata, instance_type)
        self.assertEqual(example, metadata)

        metadata = {}
        instance_types.save_instance_type_info(metadata, instance_type, 'foo')
        self.assertEqual(example_prefix, metadata)
Ejemplo n.º 15
0
 def test_allocate_for_instance_handles_macs_passed(self):
     # If a macs argument is supplied to the 'nova-network' API, it is just
     # ignored. This test checks that the call down to the rpcapi layer
     # doesn't pass macs down: nova-network doesn't support hypervisor
     # mac address limits (today anyhow).
     macs = set(['ab:cd:ef:01:23:34'])
     self.mox.StubOutWithMock(
         self.network_api.network_rpcapi, "allocate_for_instance")
     kwargs = dict(zip(['host', 'instance_id', 'project_id',
             'requested_networks', 'rxtx_factor', 'vpn', 'macs'],
             itertools.repeat(mox.IgnoreArg())))
     self.network_api.network_rpcapi.allocate_for_instance(
         mox.IgnoreArg(), **kwargs).AndReturn([])
     self.mox.ReplayAll()
     inst_type = instance_types.get_default_instance_type()
     inst_type['rxtx_factor'] = 0
     sys_meta = instance_types.save_instance_type_info({}, inst_type)
     instance = dict(id='id', uuid='uuid', project_id='project_id',
         host='host', system_metadata=utils.dict_to_metadata(sys_meta))
     self.network_api.allocate_for_instance(
         self.context, instance, 'vpn', 'requested_networks', macs=macs)
Ejemplo n.º 16
0
    def _stub_migrate_instance_calls(self, method, multi_host, info):
        fake_instance_type = instance_types.get_default_instance_type()
        fake_instance_type['rxtx_factor'] = 1.21
        sys_meta = utils.dict_to_metadata(
            instance_types.save_instance_type_info({}, fake_instance_type))
        fake_instance = {'uuid': 'fake_uuid',
                         'instance_type_id': fake_instance_type['id'],
                         'project_id': 'fake_project_id',
                         'system_metadata': sys_meta}
        fake_migration = {'source_compute': 'fake_compute_source',
                          'dest_compute': 'fake_compute_dest'}

        def fake_mig_inst_method(*args, **kwargs):
            info['kwargs'] = kwargs

        def fake_is_multi_host(*args, **kwargs):
            return multi_host

        def fake_get_floaters(*args, **kwargs):
            return ['fake_float1', 'fake_float2']

        self.stubs.Set(network_rpcapi.NetworkAPI, method,
                fake_mig_inst_method)
        self.stubs.Set(self.network_api, '_is_multi_host',
                fake_is_multi_host)
        self.stubs.Set(self.network_api, '_get_floating_ip_addresses',
                fake_get_floaters)

        expected = {'instance_uuid': 'fake_uuid',
                    'source_compute': 'fake_compute_source',
                    'dest_compute': 'fake_compute_dest',
                    'rxtx_factor': 1.21,
                    'project_id': 'fake_project_id',
                    'floating_addresses': None}
        if multi_host:
            expected['floating_addresses'] = ['fake_float1', 'fake_float2']
        return fake_instance, fake_migration, expected
Ejemplo n.º 17
0
 def test_will_get_instance_by_flavor_id(self):
     default_instance_type = instance_types.get_default_instance_type()
     flavorid = default_instance_type['flavorid']
     fetched = instance_types.get_instance_type_by_flavor_id(flavorid)
     self.assertEqual(default_instance_type, fetched)
Ejemplo n.º 18
0
 def test_instance_type_get_by_None_name_returns_default(self):
     """Ensure get by name returns default flavor with no name"""
     default = instance_types.get_default_instance_type()
     actual = instance_types.get_instance_type_by_name(None)
     self.assertEqual(default, actual)
Ejemplo n.º 19
0
    def create(self,
               context,
               instance_type,
               image_id,
               kernel_id=None,
               ramdisk_id=None,
               min_count=1,
               max_count=1,
               display_name='',
               display_description='',
               key_name=None,
               key_data=None,
               security_group='default',
               availability_zone=None,
               user_data=None,
               metadata={},
               injected_files=None):
        """Create the number and type of instances requested.

        Verifies that quota and other arguments are valid.

        """
        if not instance_type:
            instance_type = instance_types.get_default_instance_type()

        num_instances = quota.allowed_instances(context, max_count,
                                                instance_type)
        if num_instances < min_count:
            pid = context.project_id
            LOG.warn(
                _("Quota exceeeded for %(pid)s,"
                  " tried to run %(min_count)s instances") % locals())
            raise quota.QuotaError(
                _("Instance quota exceeded. You can only "
                  "run %s more instances of this type.") % num_instances,
                "InstanceLimitExceeded")

        self._check_metadata_properties_quota(context, metadata)
        self._check_injected_file_quota(context, injected_files)

        image = self.image_service.show(context, image_id)

        os_type = None
        if 'properties' in image and 'os_type' in image['properties']:
            os_type = image['properties']['os_type']

        if kernel_id is None:
            kernel_id = image['properties'].get('kernel_id', None)
        if ramdisk_id is None:
            ramdisk_id = image['properties'].get('ramdisk_id', None)
        # FIXME(sirp): is there a way we can remove null_kernel?
        # No kernel and ramdisk for raw images
        if kernel_id == str(FLAGS.null_kernel):
            kernel_id = None
            ramdisk_id = None
            LOG.debug(_("Creating a raw instance"))
        # Make sure we have access to kernel and ramdisk (if not raw)
        logging.debug("Using Kernel=%s, Ramdisk=%s" % (kernel_id, ramdisk_id))
        if kernel_id:
            self.image_service.show(context, kernel_id)
        if ramdisk_id:
            self.image_service.show(context, ramdisk_id)

        if security_group is None:
            security_group = ['default']
        if not type(security_group) is list:
            security_group = [security_group]

        security_groups = []
        self.ensure_default_security_group(context)
        for security_group_name in security_group:
            group = db.security_group_get_by_name(context, context.project_id,
                                                  security_group_name)
            security_groups.append(group['id'])

        if key_data is None and key_name:
            key_pair = db.key_pair_get(context, context.user_id, key_name)
            key_data = key_pair['public_key']

        base_options = {
            'reservation_id': utils.generate_uid('r'),
            'image_id': image_id,
            'kernel_id': kernel_id or '',
            'ramdisk_id': ramdisk_id or '',
            'state': 0,
            'state_description': 'scheduling',
            'user_id': context.user_id,
            'project_id': context.project_id,
            'launch_time': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
            'instance_type_id': instance_type['id'],
            'memory_mb': instance_type['memory_mb'],
            'vcpus': instance_type['vcpus'],
            'local_gb': instance_type['local_gb'],
            'display_name': display_name,
            'display_description': display_description,
            'user_data': user_data or '',
            'key_name': key_name,
            'key_data': key_data,
            'locked': False,
            'metadata': metadata,
            'availability_zone': availability_zone,
            'os_type': os_type
        }
        elevated = context.elevated()
        instances = []
        LOG.debug(_("Going to run %s instances..."), num_instances)
        for num in range(num_instances):
            instance = dict(mac_address=utils.generate_mac(),
                            launch_index=num,
                            **base_options)
            instance = self.db.instance_create(context, instance)
            instance_id = instance['id']

            elevated = context.elevated()
            if not security_groups:
                security_groups = []
            for security_group_id in security_groups:
                self.db.instance_add_security_group(elevated, instance_id,
                                                    security_group_id)

            # Set sane defaults if not specified
            updates = dict(hostname=self.hostname_factory(instance_id))
            if (not hasattr(instance, 'display_name')
                    or instance.display_name is None):
                updates['display_name'] = "Server %s" % instance_id

            instance = self.update(context, instance_id, **updates)
            instances.append(instance)

            pid = context.project_id
            uid = context.user_id
            LOG.debug(
                _("Casting to scheduler for %(pid)s/%(uid)s's"
                  " instance %(instance_id)s") % locals())
            rpc.cast(
                context, FLAGS.scheduler_topic, {
                    "method": "run_instance",
                    "args": {
                        "topic": FLAGS.compute_topic,
                        "instance_id": instance_id,
                        "availability_zone": availability_zone,
                        "injected_files": injected_files
                    }
                })

        for group_id in security_groups:
            self.trigger_security_group_members_refresh(elevated, group_id)

        return [dict(x.iteritems()) for x in instances]
Ejemplo n.º 20
0
 def test_will_get_instance_by_flavor_id(self):
     default_instance_type = instance_types.get_default_instance_type()
     flavorid = default_instance_type['flavorid']
     fetched = instance_types.get_instance_type_by_flavor_id(flavorid)
     self.assertEqual(default_instance_type, fetched)
Ejemplo n.º 21
0
 def test_will_not_get_instance_type_by_name_with_no_name(self):
     """Ensure get by name returns default flavor with no name"""
     self.assertEqual(instance_types.get_default_instance_type(),
                      instance_types.get_instance_type_by_name(None))
Ejemplo n.º 22
0
def get_default_sys_meta():
    return utils.dict_to_metadata(
        instance_types.save_instance_type_info(
            {}, instance_types.get_default_instance_type()))
Ejemplo n.º 23
0
    def _check_create_parameters(self, context, instance_type,
               image_href, kernel_id=None, ramdisk_id=None,
               min_count=None, max_count=None,
               display_name='', display_description='',
               key_name=None, key_data=None, security_group='default',
               availability_zone=None, user_data=None, metadata={},
               injected_files=None, admin_password=None, zone_blob=None,
               reservation_id=None):
        """Verify all the input parameters regardless of the provisioning
        strategy being performed."""

        if not instance_type:
            instance_type = instance_types.get_default_instance_type()
        if not min_count:
            min_count = 1
        if not max_count:
            max_count = min_count

        num_instances = quota.allowed_instances(context, max_count,
                                                instance_type)
        if num_instances < min_count:
            pid = context.project_id
            LOG.warn(_("Quota exceeeded for %(pid)s,"
                    " tried to run %(min_count)s instances") % locals())
            if num_instances <= 0:
                message = _("Instance quota exceeded. You cannot run any "
                            "more instances of this type.")
            else:
                message = _("Instance quota exceeded. You can only run %s "
                            "more instances of this type.") % num_instances
            raise quota.QuotaError(message, "InstanceLimitExceeded")

        self._check_metadata_properties_quota(context, metadata)
        self._check_injected_file_quota(context, injected_files)

        (image_service, image_id) = nova.image.get_image_service(image_href)
        image = image_service.show(context, image_id)

        os_type = None
        if 'properties' in image and 'os_type' in image['properties']:
            os_type = image['properties']['os_type']
        architecture = None
        if 'properties' in image and 'arch' in image['properties']:
            architecture = image['properties']['arch']
        vm_mode = None
        if 'properties' in image and 'vm_mode' in image['properties']:
            vm_mode = image['properties']['vm_mode']

        if kernel_id is None:
            kernel_id = image['properties'].get('kernel_id', None)
        if ramdisk_id is None:
            ramdisk_id = image['properties'].get('ramdisk_id', None)
        # FIXME(sirp): is there a way we can remove null_kernel?
        # No kernel and ramdisk for raw images
        if kernel_id == str(FLAGS.null_kernel):
            kernel_id = None
            ramdisk_id = None
            LOG.debug(_("Creating a raw instance"))
        # Make sure we have access to kernel and ramdisk (if not raw)
        logging.debug("Using Kernel=%s, Ramdisk=%s" %
                       (kernel_id, ramdisk_id))
        if kernel_id:
            image_service.show(context, kernel_id)
        if ramdisk_id:
            image_service.show(context, ramdisk_id)

        self.ensure_default_security_group(context)

        if key_data is None and key_name:
            key_pair = db.key_pair_get(context, context.user_id, key_name)
            key_data = key_pair['public_key']

        if reservation_id is None:
            reservation_id = utils.generate_uid('r')

        root_device_name = ec2utils.properties_root_device_name(
            image['properties'])

        base_options = {
            'reservation_id': reservation_id,
            'image_ref': image_href,
            'kernel_id': kernel_id or '',
            'ramdisk_id': ramdisk_id or '',
            'state': 0,
            'state_description': 'scheduling',
            'user_id': context.user_id,
            'project_id': context.project_id,
            'launch_time': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
            'instance_type_id': instance_type['id'],
            'memory_mb': instance_type['memory_mb'],
            'vcpus': instance_type['vcpus'],
            'local_gb': instance_type['local_gb'],
            'display_name': display_name,
            'display_description': display_description,
            'user_data': user_data or '',
            'key_name': key_name,
            'key_data': key_data,
            'locked': False,
            'metadata': metadata,
            'availability_zone': availability_zone,
            'os_type': os_type,
            'architecture': architecture,
            'vm_mode': vm_mode,
            'root_device_name': root_device_name}

        return (num_instances, base_options, image)
Ejemplo n.º 24
0
    def create(self, context, instance_type,
               image_id, kernel_id=None, ramdisk_id=None,
               min_count=1, max_count=1,
               display_name='', display_description='',
               key_name=None, key_data=None, security_group='default',
               availability_zone=None, user_data=None, metadata={},
               injected_files=None):
        """Create the number and type of instances requested.

        Verifies that quota and other arguments are valid.

        """
        if not instance_type:
            instance_type = instance_types.get_default_instance_type()

        num_instances = quota.allowed_instances(context, max_count,
                                                instance_type)
        if num_instances < min_count:
            pid = context.project_id
            LOG.warn(_("Quota exceeeded for %(pid)s,"
                    " tried to run %(min_count)s instances") % locals())
            raise quota.QuotaError(_("Instance quota exceeded. You can only "
                                     "run %s more instances of this type.") %
                                   num_instances, "InstanceLimitExceeded")

        self._check_metadata_properties_quota(context, metadata)
        self._check_injected_file_quota(context, injected_files)

        image = self.image_service.show(context, image_id)

        os_type = None
        if 'properties' in image and 'os_type' in image['properties']:
            os_type = image['properties']['os_type']

        if kernel_id is None:
            kernel_id = image['properties'].get('kernel_id', None)
        if ramdisk_id is None:
            ramdisk_id = image['properties'].get('ramdisk_id', None)
        # FIXME(sirp): is there a way we can remove null_kernel?
        # No kernel and ramdisk for raw images
        if kernel_id == str(FLAGS.null_kernel):
            kernel_id = None
            ramdisk_id = None
            LOG.debug(_("Creating a raw instance"))
        # Make sure we have access to kernel and ramdisk (if not raw)
        logging.debug("Using Kernel=%s, Ramdisk=%s" %
                       (kernel_id, ramdisk_id))
        if kernel_id:
            self.image_service.show(context, kernel_id)
        if ramdisk_id:
            self.image_service.show(context, ramdisk_id)

        if security_group is None:
            security_group = ['default']
        if not type(security_group) is list:
            security_group = [security_group]

        security_groups = []
        self.ensure_default_security_group(context)
        for security_group_name in security_group:
            group = db.security_group_get_by_name(context,
                                                  context.project_id,
                                                  security_group_name)
            security_groups.append(group['id'])

        if key_data is None and key_name:
            key_pair = db.key_pair_get(context, context.user_id, key_name)
            key_data = key_pair['public_key']

        base_options = {
            'reservation_id': utils.generate_uid('r'),
            'image_id': image_id,
            'kernel_id': kernel_id or '',
            'ramdisk_id': ramdisk_id or '',
            'state': 0,
            'state_description': 'scheduling',
            'user_id': context.user_id,
            'project_id': context.project_id,
            'launch_time': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
            'instance_type_id': instance_type['id'],
            'memory_mb': instance_type['memory_mb'],
            'vcpus': instance_type['vcpus'],
            'local_gb': instance_type['local_gb'],
            'display_name': display_name,
            'display_description': display_description,
            'user_data': user_data or '',
            'key_name': key_name,
            'key_data': key_data,
            'locked': False,
            'metadata': metadata,
            'availability_zone': availability_zone,
            'os_type': os_type}
        elevated = context.elevated()
        instances = []
        LOG.debug(_("Going to run %s instances..."), num_instances)
        for num in range(num_instances):
            instance = dict(mac_address=utils.generate_mac(),
                            launch_index=num,
                            **base_options)
            instance = self.db.instance_create(context, instance)
            instance_id = instance['id']

            elevated = context.elevated()
            if not security_groups:
                security_groups = []
            for security_group_id in security_groups:
                self.db.instance_add_security_group(elevated,
                                                    instance_id,
                                                    security_group_id)

            # Set sane defaults if not specified
            updates = dict(hostname=self.hostname_factory(instance_id))
            if (not hasattr(instance, 'display_name') or
                    instance.display_name is None):
                updates['display_name'] = "Server %s" % instance_id

            instance = self.update(context, instance_id, **updates)
            instances.append(instance)

            pid = context.project_id
            uid = context.user_id
            LOG.debug(_("Casting to scheduler for %(pid)s/%(uid)s's"
                    " instance %(instance_id)s") % locals())
            rpc.cast(context,
                     FLAGS.scheduler_topic,
                     {"method": "run_instance",
                      "args": {"topic": FLAGS.compute_topic,
                               "instance_id": instance_id,
                               "availability_zone": availability_zone,
                               "injected_files": injected_files}})

        for group_id in security_groups:
            self.trigger_security_group_members_refresh(elevated, group_id)

        return [dict(x.iteritems()) for x in instances]
Ejemplo n.º 25
0
Archivo: api.py Proyecto: ed-/reddwarf
    def create(
        self,
        context,
        instance_type,
        image_id,
        kernel_id=None,
        ramdisk_id=None,
        min_count=1,
        max_count=1,
        display_name="",
        display_description="",
        key_name=None,
        key_data=None,
        security_group="default",
        availability_zone=None,
        user_data=None,
        metadata={},
        injected_files=None,
        admin_password=None,
    ):
        """Create the number and type of instances requested.

        Verifies that quota and other arguments are valid.

        """
        if not instance_type:
            instance_type = instance_types.get_default_instance_type()

        num_instances = quota.allowed_instances(context, max_count, instance_type)
        if num_instances < min_count:
            pid = context.project_id
            LOG.warn(_("Quota exceeeded for %(pid)s," " tried to run %(min_count)s instances") % locals())
            if num_instances <= 0:
                message = _("Instance quota exceeded. You cannot run any " "more instances of this type.")
            else:
                message = (
                    _("Instance quota exceeded. You can only run %s " "more instances of this type.") % num_instances
                )
            raise quota.QuotaError(message, "InstanceLimitExceeded")

        self._check_metadata_properties_quota(context, metadata)
        self._check_injected_file_quota(context, injected_files)

        image = self.image_service.show(context, image_id)

        os_type = None
        if "properties" in image and "os_type" in image["properties"]:
            os_type = image["properties"]["os_type"]

        if kernel_id is None:
            kernel_id = image["properties"].get("kernel_id", None)
        if ramdisk_id is None:
            ramdisk_id = image["properties"].get("ramdisk_id", None)
        # FIXME(sirp): is there a way we can remove null_kernel?
        # No kernel and ramdisk for raw images
        if kernel_id == str(FLAGS.null_kernel):
            kernel_id = None
            ramdisk_id = None
            LOG.debug(_("Creating a raw instance"))
        # Make sure we have access to kernel and ramdisk (if not raw)
        logging.debug("Using Kernel=%s, Ramdisk=%s" % (kernel_id, ramdisk_id))
        if kernel_id:
            self.image_service.show(context, kernel_id)
        if ramdisk_id:
            self.image_service.show(context, ramdisk_id)

        if security_group is None:
            security_group = ["default"]
        if not type(security_group) is list:
            security_group = [security_group]

        security_groups = []
        self.ensure_default_security_group(context)
        for security_group_name in security_group:
            group = db.security_group_get_by_name(context, context.project_id, security_group_name)
            security_groups.append(group["id"])

        if key_data is None and key_name:
            key_pair = db.key_pair_get(context, context.user_id, key_name)
            key_data = key_pair["public_key"]

        base_options = {
            "reservation_id": utils.generate_uid("r"),
            "image_id": image_id,
            "kernel_id": kernel_id or "",
            "ramdisk_id": ramdisk_id or "",
            "state": 0,
            "state_description": "scheduling",
            "user_id": context.user_id,
            "project_id": context.project_id,
            "launch_time": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "instance_type_id": instance_type["id"],
            "memory_mb": instance_type["memory_mb"],
            "vcpus": instance_type["vcpus"],
            "local_gb": instance_type["local_gb"],
            "display_name": display_name,
            "display_description": display_description,
            "user_data": user_data or "",
            "key_name": key_name,
            "key_data": key_data,
            "locked": False,
            "metadata": metadata,
            "availability_zone": availability_zone,
            "os_type": os_type,
        }
        elevated = context.elevated()
        instances = []
        LOG.debug(_("Going to run %s instances..."), num_instances)
        for num in range(num_instances):
            instance = dict(mac_address=utils.generate_mac(), launch_index=num, **base_options)
            instance = self.db.instance_create(context, instance)
            instance_id = instance["id"]

            elevated = context.elevated()
            if not security_groups:
                security_groups = []
            for security_group_id in security_groups:
                self.db.instance_add_security_group(elevated, instance_id, security_group_id)

            # Set sane defaults if not specified
            updates = dict(hostname=self.hostname_factory(instance_id))
            if not hasattr(instance, "display_name") or instance.display_name is None:
                updates["display_name"] = "Server %s" % instance_id

            instance = self.update(context, instance_id, **updates)
            instances.append(instance)

            pid = context.project_id
            uid = context.user_id
            LOG.debug(_("Casting to scheduler for %(pid)s/%(uid)s's" " instance %(instance_id)s") % locals())

            # NOTE(sandy): For now we're just going to pass in the
            # instance_type record to the scheduler. In a later phase
            # we'll be ripping this whole for-loop out and deferring the
            # creation of the Instance record. At that point all this will
            # change.
            rpc.cast(
                context,
                FLAGS.scheduler_topic,
                {
                    "method": "run_instance",
                    "args": {
                        "topic": FLAGS.compute_topic,
                        "instance_id": instance_id,
                        "instance_type": instance_type,
                        "availability_zone": availability_zone,
                        "injected_files": injected_files,
                        "admin_password": admin_password,
                    },
                },
            )

        for group_id in security_groups:
            self.trigger_security_group_members_refresh(elevated, group_id)

        return [dict(x.iteritems()) for x in instances]
Ejemplo n.º 26
0
 def get_instance_type(self, context, flavor_type):
     if flavor_type == 1:
         return instance_types.get_default_instance_type()
     else:
         raise exception.InstanceTypeNotFound(flavor_type)
 def get_instance_type(self, context, flavor_type):
     if flavor_type == 1:
         return instance_types.get_default_instance_type()
     else:
         raise exception.InstanceTypeNotFound(flavor_type)
Ejemplo n.º 28
0
    def apply(self, context, resource):

        if not resource.metadata:
            resource.metadata = {}
        if not resource.security_group:
            resource.security_group = 'default'

        if not resource.instance_type:
            resource.instance_type = instance_types.get_default_instance_type()
        if not resource.min_count:
            resource.min_count = 1
        if not resource.max_count:
            resource.max_count = resource.min_count

        resource.block_device_mapping = resource.block_device_mapping or []
        if resource.instance_type['disabled']:
            raise exception.InstanceTypeNotFound(
                    instance_type_id=resource.instance_type['id'])

        if resource.user_data:
            l = len(resource.user_data)
            if l > MAX_USERDATA_SIZE:
                # NOTE(mikal): user_data is stored in a text column, and
                # the database might silently truncate if its over length.
                raise exception.InstanceUserDataTooLarge(
                    length=l, maxsize=MAX_USERDATA_SIZE)

            try:
                base64.decodestring(resource.user_data)
            except base64.binascii.Error:
                raise exception.InstanceUserDataMalformed()

        # Reserve quotas
        resource.num_instances, resource.quota_reservations = \
                        self._check_num_instances_quota(context,
                                                        resource.instance_type,
                                                        resource.min_count,
                                                        resource.max_count)

        self._check_metadata_properties_quota(context, resource.metadata)
        self._check_injected_file_quota(context, resource.injected_files)
        self._check_requested_networks(context, resource.requested_networks)

        # Handle config_drive
        resource.config_drive_id = None
        if resource.config_drive and not utils.is_valid_boolstr(
                                                        resource.config_drive):
            # config_drive is volume id
            resource.config_drive_id = resource.config_drive
            resource.config_drive = None

            # Ensure config_drive image exists
            cd_image_service, config_drive_id = \
                      glance.get_remote_image_service(context,
                                                      resource.config_drive_id)
            cd_image_service.show(context, resource.config_drive_id)

        if resource.key_data is None and resource.key_name:
            resource.key_pair = self.db.key_pair_get(context, context.user_id,
                                            resource.key_name)
            resource.key_data = resource.key_pair['public_key']

        resource.root_device_name = block_device.properties_root_device_name(
                                          resource.image.get('properties', {}))

        resource.availability_zone, resource.forced_host = \
                     self._handle_availability_zone(resource.availability_zone)

        resource.system_metadata = instance_types.save_instance_type_info(
                                dict(), resource.instance_type)

        return orc_utils.DictableObject(details='request_validated',
                                        resource=resource)
Ejemplo n.º 29
0
 def test_instance_type_get_by_None_name_returns_default(self):
     # Ensure get by name returns default flavor with no name.
     default = instance_types.get_default_instance_type()
     actual = instance_types.get_instance_type_by_name(None)
     self.assertEqual(default, actual)
 def test_will_get_instance_type_by_id(self):
     default_instance_type = instance_types.get_default_instance_type()
     instance_type_id = default_instance_type["id"]
     fetched = instance_types.get_instance_type(instance_type_id)
     self.assertEqual(default_instance_type, fetched)
Ejemplo n.º 31
0
 def test_will_not_get_instance_type_by_name_with_no_name(self):
     """Ensure get by name returns default flavor with no name"""
     self.assertEqual(instance_types.get_default_instance_type(),
                           instance_types.get_instance_type_by_name(None))
Ejemplo n.º 32
0
def get_default_sys_meta():
    return utils.dict_to_metadata(
        instance_types.save_instance_type_info(
            {}, instance_types.get_default_instance_type()))