예제 #1
0
 def test_flavor_create_frozen(self):
     ctx = context.get_admin_context()
     db.flavor_create(ctx, {
         'name': 'foo', 'memory_mb': 512, 'vcpus': 1,
         'root_gb': 1, 'ephemeral_gb': 0, 'flavorid': 'foo',
         'swap': 0, 'rxtx_factor': 1.0, 'vcpu_weight': 1,
         'disabled': False, 'is_public': True,
     })
     new_flav = {'flavor': rand_flavor()}
     resp = self.api.api_post('flavors', new_flav,
                              check_response_status=False)
     self.assertEqual(409, resp.status)
 def test_flavor_create_frozen(self):
     ctx = context.get_admin_context()
     db.flavor_create(ctx, {
         'name': 'foo', 'memory_mb': 512, 'vcpus': 1,
         'root_gb': 1, 'ephemeral_gb': 0, 'flavorid': 'foo',
         'swap': 0, 'rxtx_factor': 1.0, 'vcpu_weight': 1,
         'disabled': False, 'is_public': True,
     })
     new_flav = {'flavor': rand_flavor()}
     resp = self.api.api_post('flavors', new_flav,
                              check_response_status=False)
     self.assertEqual(409, resp.status)
예제 #3
0
파일: flavor.py 프로젝트: gilmeir/nova
 def create(self, context):
     if self.obj_attr_is_set("id"):
         raise exception.ObjectActionError(action="create", reason="already created")
     updates = self.obj_get_changes()
     expected_attrs = []
     for attr in OPTIONAL_FIELDS:
         if attr in updates:
             expected_attrs.append(attr)
     projects = updates.pop("projects", [])
     db_flavor = db.flavor_create(context, updates, projects=projects)
     self._from_db_object(context, self, db_flavor, expected_attrs=expected_attrs)
 def test_flavor_create_frozen(self):
     ctx = context.get_admin_context()
     db.flavor_create(
         ctx,
         {
             "name": "foo",
             "memory_mb": 512,
             "vcpus": 1,
             "root_gb": 1,
             "ephemeral_gb": 0,
             "flavorid": "foo",
             "swap": 0,
             "rxtx_factor": 1.0,
             "vcpu_weight": 1,
             "disabled": False,
             "is_public": True,
         },
     )
     new_flav = {"flavor": rand_flavor()}
     resp = self.api.api_post("flavors", new_flav, check_response_status=False)
     self.assertEqual(409, resp.status)
예제 #5
0
 def create(self, context):
     if self.obj_attr_is_set('id'):
         raise exception.ObjectActionError(action='create',
                                           reason='already created')
     updates = self.obj_get_changes()
     expected_attrs = []
     for attr in OPTIONAL_FIELDS:
         if attr in updates:
             expected_attrs.append(attr)
     projects = updates.pop('projects', [])
     db_flavor = db.flavor_create(context, updates, projects=projects)
     self._from_db_object(context, self, db_flavor,
                          expected_attrs=expected_attrs)
예제 #6
0
    def _create_disabled_instance_type(self):
        inst_types = db.flavor_get_all(self.admin_context)

        inst_type = inst_types[0]

        del inst_type["id"]
        inst_type["name"] += ".disabled"
        inst_type["flavorid"] = six.text_type(max([int(flavor["flavorid"]) for flavor in inst_types]) + 1)
        inst_type["disabled"] = True

        disabled_type = db.flavor_create(self.admin_context, inst_type)

        return disabled_type
    def _create_disabled_instance_type(self):
        inst_types = db.flavor_get_all(self.admin_context)

        inst_type = inst_types[0]

        del inst_type['id']
        inst_type['name'] += '.disabled'
        inst_type['flavorid'] = unicode(
            max([int(flavor['flavorid']) for flavor in inst_types]) + 1)
        inst_type['disabled'] = True

        disabled_type = db.flavor_create(self.admin_context, inst_type)

        return disabled_type
예제 #8
0
    def _create_disabled_instance_type(self):
        inst_types = db.flavor_get_all(self.admin_context)

        inst_type = inst_types[0]

        del inst_type['id']
        inst_type['name'] += '.disabled'
        inst_type['flavorid'] = six.text_type(max(
                [int(flavor['flavorid']) for flavor in inst_types]) + 1)
        inst_type['disabled'] = True

        disabled_type = db.flavor_create(
                self.admin_context, inst_type)

        return disabled_type
예제 #9
0
    def setUp(self):
        super(FlavorCommandsTestCase, self).setUp()

        values = dict(name="test.small",
                      memory_mb=220,
                      vcpus=1,
                      root_gb=16,
                      ephemeral_gb=32,
                      flavorid=105)
        ref = db.flavor_create(context.get_admin_context(), values)
        self.instance_type_name = ref["name"]
        self.instance_type_id = ref["id"]
        self.instance_type_flavorid = ref["flavorid"]
        self.set_key = manage.FlavorCommands().set_key
        self.unset_key = manage.FlavorCommands().unset_key
예제 #10
0
    def setUp(self):
        super(InstanceTypeCommandsTestCase, self).setUp()

        values = dict(name="test.small",
                      memory_mb=220,
                      vcpus=1,
                      root_gb=16,
                      ephemeral_gb=32,
                      flavorid=105)
        ref = db.flavor_create(context.get_admin_context(),
                                      values)
        self.instance_type_name = ref["name"]
        self.instance_type_id = ref["id"]
        self.instance_type_flavorid = ref["flavorid"]
        self.set_key = manage.InstanceTypeCommands().set_key
        self.unset_key = manage.InstanceTypeCommands().unset_key
 def setUp(self):
     super(InstanceTypeExtraSpecsTestCase, self).setUp()
     self.context = context.get_admin_context()
     values = dict(name="cg1.4xlarge",
                   memory_mb=22000,
                   vcpus=8,
                   root_gb=1690,
                   ephemeral_gb=2000,
                   flavorid=105)
     self.specs = dict(cpu_arch=arch.X86_64,
                       cpu_model="Nehalem",
                       xpu_arch="fermi",
                       xpus="2",
                       xpu_model="Tesla 2050")
     values['extra_specs'] = self.specs
     ref = db.flavor_create(self.context, values)
     self.instance_type_id = ref["id"]
     self.flavorid = ref["flavorid"]
예제 #12
0
 def setUp(self):
     super(InstanceTypeExtraSpecsTestCase, self).setUp()
     self.context = context.get_admin_context()
     values = dict(name="cg1.4xlarge",
                   memory_mb=22000,
                   vcpus=8,
                   root_gb=1690,
                   ephemeral_gb=2000,
                   flavorid=105)
     self.specs = dict(cpu_arch=arch.X86_64,
                       cpu_model="Nehalem",
                       xpu_arch="fermi",
                       xpus="2",
                       xpu_model="Tesla 2050")
     values['extra_specs'] = self.specs
     ref = db.flavor_create(self.context,
                            values)
     self.instance_type_id = ref["id"]
     self.flavorid = ref["flavorid"]
예제 #13
0
def create(name,
           memory,
           vcpus,
           root_gb,
           ephemeral_gb=0,
           flavorid=None,
           swap=0,
           rxtx_factor=1.0,
           is_public=True):
    """Creates flavors."""
    if not flavorid:
        flavorid = uuid.uuid4()

    kwargs = {
        'memory_mb': memory,
        'vcpus': vcpus,
        'root_gb': root_gb,
        'ephemeral_gb': ephemeral_gb,
        'swap': swap,
        'rxtx_factor': rxtx_factor,
    }

    if isinstance(name, six.string_types):
        name = name.strip()
    # ensure name do not exceed 255 characters
    utils.check_string_length(name, 'name', min_length=1, max_length=255)

    # ensure name does not contain any special characters
    valid_name = VALID_NAME_REGEX.search(name)
    if not valid_name:
        msg = _("Flavor names can only contain alphanumeric characters, "
                "periods, dashes, underscores and spaces.")
        raise exception.InvalidInput(reason=msg)

    # NOTE(vish): Internally, flavorid is stored as a string but it comes
    #             in through json as an integer, so we convert it here.
    flavorid = unicode(flavorid)

    # ensure leading/trailing whitespaces not present.
    if flavorid.strip() != flavorid:
        msg = _("id cannot contain leading and/or trailing whitespace(s)")
        raise exception.InvalidInput(reason=msg)

    # ensure flavor id does not exceed 255 characters
    utils.check_string_length(flavorid, 'id', min_length=1, max_length=255)

    # ensure flavor id does not contain any special characters
    valid_flavor_id = VALID_ID_REGEX.search(flavorid)
    if not valid_flavor_id:
        msg = _("Flavor id can only contain letters from A-Z (both cases), "
                "periods, dashes, underscores and spaces.")
        raise exception.InvalidInput(reason=msg)

    # NOTE(wangbo): validate attributes of the creating flavor.
    # ram and vcpus should be positive ( > 0) integers.
    # disk, ephemeral and swap should be non-negative ( >= 0) integers.
    flavor_attributes = {
        'memory_mb': ('ram', 1),
        'vcpus': ('vcpus', 1),
        'root_gb': ('disk', 0),
        'ephemeral_gb': ('ephemeral', 0),
        'swap': ('swap', 0)
    }

    for key, value in flavor_attributes.items():
        kwargs[key] = utils.validate_integer(kwargs[key], value[0], value[1],
                                             db.MAX_INT)

    # rxtx_factor should be a positive float
    try:
        kwargs['rxtx_factor'] = float(kwargs['rxtx_factor'])
        if (kwargs['rxtx_factor'] <= 0
                or kwargs['rxtx_factor'] > SQL_SP_FLOAT_MAX):
            raise ValueError()
    except ValueError:
        msg = (_("'rxtx_factor' argument must be a float between 0 and %g") %
               SQL_SP_FLOAT_MAX)
        raise exception.InvalidInput(reason=msg)

    kwargs['name'] = name
    kwargs['flavorid'] = flavorid
    # ensure is_public attribute is boolean
    try:
        kwargs['is_public'] = strutils.bool_from_string(is_public, strict=True)
    except ValueError:
        raise exception.InvalidInput(reason=_("is_public must be a boolean"))

    try:
        return db.flavor_create(context.get_admin_context(), kwargs)
    except db_exc.DBError as e:
        LOG.exception(_LE('DB error: %s'), e)
        raise exception.FlavorCreateFailed()
예제 #14
0
파일: flavors.py 프로젝트: LeoDuo/nova
def create(name, memory, vcpus, root_gb, ephemeral_gb=0, flavorid=None,
           swap=0, rxtx_factor=1.0, is_public=True):
    """Creates flavors."""
    if not flavorid:
        flavorid = uuid.uuid4()

    kwargs = {
        'memory_mb': memory,
        'vcpus': vcpus,
        'root_gb': root_gb,
        'ephemeral_gb': ephemeral_gb,
        'swap': swap,
        'rxtx_factor': rxtx_factor,
    }

    # ensure name do not exceed 255 characters
    utils.check_string_length(name, 'name', min_length=1, max_length=255)

    # ensure name does not contain any special characters
    valid_name = VALID_NAME_OR_ID_REGEX.search(name)
    if not valid_name:
        msg = _("names can only contain [a-zA-Z0-9_.- ]")
        raise exception.InvalidInput(reason=msg)

    # NOTE(vish): Internally, flavorid is stored as a string but it comes
    #             in through json as an integer, so we convert it here.
    flavorid = unicode(flavorid)

    # ensure leading/trailing whitespaces not present.
    if flavorid.strip() != flavorid:
        msg = _("id cannot contain leading and/or trailing whitespace(s)")
        raise exception.InvalidInput(reason=msg)

    # ensure flavor id does not exceed 255 characters
    utils.check_string_length(flavorid, 'id', min_length=1,
                              max_length=255)

    # ensure flavor id does not contain any special characters
    valid_flavor_id = VALID_NAME_OR_ID_REGEX.search(flavorid)
    if not valid_flavor_id:
        msg = _("id can only contain [a-zA-Z0-9_.- ]")
        raise exception.InvalidInput(reason=msg)

    # Some attributes are positive ( > 0) integers
    for option in ['memory_mb', 'vcpus']:
        kwargs[option] = utils.validate_integer(kwargs[option], option, 1,
                                                sys.maxint)

    # Some attributes are non-negative ( >= 0) integers
    for option in ['root_gb', 'ephemeral_gb', 'swap']:
        kwargs[option] = utils.validate_integer(kwargs[option], option, 0,
                                                sys.maxint)

    # rxtx_factor should be a positive float
    try:
        kwargs['rxtx_factor'] = float(kwargs['rxtx_factor'])
        if kwargs['rxtx_factor'] <= 0:
            raise ValueError()
    except ValueError:
        msg = _("'rxtx_factor' argument must be a positive float")
        raise exception.InvalidInput(reason=msg)

    kwargs['name'] = name
    kwargs['flavorid'] = flavorid
    # ensure is_public attribute is boolean
    try:
        kwargs['is_public'] = strutils.bool_from_string(
            is_public, strict=True)
    except ValueError:
        raise exception.InvalidInput(reason=_("is_public must be a boolean"))

    try:
        return db.flavor_create(context.get_admin_context(), kwargs)
    except db_exc.DBError as e:
        LOG.exception(_('DB error: %s') % e)
        raise exception.InstanceTypeCreateFailed()
예제 #15
0
파일: flavors.py 프로젝트: pengkui/nova
def create(name, memory, vcpus, root_gb, ephemeral_gb=0, flavorid=None,
           swap=0, rxtx_factor=1.0, is_public=True):
    """Creates flavors."""
    if not flavorid:
        flavorid = uuid.uuid4()

    kwargs = {
        'memory_mb': memory,
        'vcpus': vcpus,
        'root_gb': root_gb,
        'ephemeral_gb': ephemeral_gb,
        'swap': swap,
        'rxtx_factor': rxtx_factor,
    }

    if isinstance(name, six.string_types):
        name = name.strip()
    # ensure name do not exceed 255 characters
    utils.check_string_length(name, 'name', min_length=1, max_length=255)

    # ensure name does not contain any special characters
    valid_name = VALID_NAME_OR_ID_REGEX.search(name)
    if not valid_name:
        msg = _("names can only contain [a-zA-Z0-9_.- ]")
        raise exception.InvalidInput(reason=msg)

    # NOTE(vish): Internally, flavorid is stored as a string but it comes
    #             in through json as an integer, so we convert it here.
    flavorid = unicode(flavorid)

    # ensure leading/trailing whitespaces not present.
    if flavorid.strip() != flavorid:
        msg = _("id cannot contain leading and/or trailing whitespace(s)")
        raise exception.InvalidInput(reason=msg)

    # ensure flavor id does not exceed 255 characters
    utils.check_string_length(flavorid, 'id', min_length=1,
                              max_length=255)

    # ensure flavor id does not contain any special characters
    valid_flavor_id = VALID_NAME_OR_ID_REGEX.search(flavorid)
    if not valid_flavor_id:
        msg = _("id can only contain [a-zA-Z0-9_.- ]")
        raise exception.InvalidInput(reason=msg)

    # Some attributes are positive ( > 0) integers
    for option in ['memory_mb', 'vcpus']:
        kwargs[option] = utils.validate_integer(kwargs[option], option, 1,
                                                sys.maxint)

    # Some attributes are non-negative ( >= 0) integers
    for option in ['root_gb', 'ephemeral_gb', 'swap']:
        kwargs[option] = utils.validate_integer(kwargs[option], option, 0,
                                                sys.maxint)

    # rxtx_factor should be a positive float
    try:
        kwargs['rxtx_factor'] = float(kwargs['rxtx_factor'])
        if kwargs['rxtx_factor'] <= 0:
            raise ValueError()
    except ValueError:
        msg = _("'rxtx_factor' argument must be a positive float")
        raise exception.InvalidInput(reason=msg)

    kwargs['name'] = name
    kwargs['flavorid'] = flavorid
    # ensure is_public attribute is boolean
    try:
        kwargs['is_public'] = strutils.bool_from_string(
            is_public, strict=True)
    except ValueError:
        raise exception.InvalidInput(reason=_("is_public must be a boolean"))

    try:
        return db.flavor_create(context.get_admin_context(), kwargs)
    except db_exc.DBError as e:
        LOG.exception(_('DB error: %s') % e)
        raise exception.InstanceTypeCreateFailed()
예제 #16
0
파일: flavors.py 프로젝트: kobtea/nova
def create(name, memory, vcpus, root_gb, ephemeral_gb=0, flavorid=None, swap=0, rxtx_factor=1.0, is_public=True):
    """Creates flavors."""
    if not flavorid:
        flavorid = uuid.uuid4()

    kwargs = {
        "memory_mb": memory,
        "vcpus": vcpus,
        "root_gb": root_gb,
        "ephemeral_gb": ephemeral_gb,
        "swap": swap,
        "rxtx_factor": rxtx_factor,
    }

    # ensure name do not exceed 255 characters
    utils.check_string_length(name, "name", min_length=1, max_length=255)

    # ensure name does not contain any special characters
    valid_name = VALID_NAME_OR_ID_REGEX.search(name)
    if not valid_name:
        msg = _("names can only contain [a-zA-Z0-9_.- ]")
        raise exception.InvalidInput(reason=msg)

    # NOTE(vish): Internally, flavorid is stored as a string but it comes
    #             in through json as an integer, so we convert it here.
    flavorid = unicode(flavorid)

    # ensure leading/trailing whitespaces not present.
    if flavorid.strip() != flavorid:
        msg = _("id cannot contain leading and/or trailing whitespace(s)")
        raise exception.InvalidInput(reason=msg)

    # ensure flavor id does not exceed 255 characters
    utils.check_string_length(flavorid, "id", min_length=1, max_length=255)

    # ensure flavor id does not contain any special characters
    valid_flavor_id = VALID_NAME_OR_ID_REGEX.search(flavorid)
    if not valid_flavor_id:
        msg = _("id can only contain [a-zA-Z0-9_.- ]")
        raise exception.InvalidInput(reason=msg)

    # Some attributes are positive ( > 0) integers
    for option in ["memory_mb", "vcpus"]:
        try:
            if int(str(kwargs[option])) <= 0:
                raise ValueError()
            kwargs[option] = int(kwargs[option])
        except (ValueError, TypeError):
            msg = _("'%s' argument must be a positive integer") % option
            raise exception.InvalidInput(reason=msg)

    # Some attributes are non-negative ( >= 0) integers
    for option in ["root_gb", "ephemeral_gb", "swap"]:
        try:
            if int(str(kwargs[option])) < 0:
                raise ValueError()
            kwargs[option] = int(kwargs[option])
        except (ValueError, TypeError):
            msg = _("'%s' argument must be an integer greater than or" " equal to 0") % option
            raise exception.InvalidInput(reason=msg)

    # rxtx_factor should be a positive float
    try:
        kwargs["rxtx_factor"] = float(kwargs["rxtx_factor"])
        if kwargs["rxtx_factor"] <= 0:
            raise ValueError()
    except ValueError:
        msg = _("'rxtx_factor' argument must be a positive float")
        raise exception.InvalidInput(reason=msg)

    kwargs["name"] = name
    kwargs["flavorid"] = flavorid
    # ensure is_public attribute is boolean
    try:
        kwargs["is_public"] = strutils.bool_from_string(is_public, strict=True)
    except ValueError:
        raise exception.InvalidInput(reason=_("is_public must be a boolean"))

    try:
        return db.flavor_create(context.get_admin_context(), kwargs)
    except db_exc.DBError as e:
        LOG.exception(_("DB error: %s") % e)
        raise exception.InstanceTypeCreateFailed()
예제 #17
0
def create(name,
           memory,
           vcpus,
           root_gb,
           ephemeral_gb=0,
           flavorid=None,
           swap=0,
           rxtx_factor=1.0,
           is_public=True):
    """Creates flavors."""
    if not flavorid:
        flavorid = uuid.uuid4()

    kwargs = {
        'memory_mb': memory,
        'vcpus': vcpus,
        'root_gb': root_gb,
        'ephemeral_gb': ephemeral_gb,
        'swap': swap,
        'rxtx_factor': rxtx_factor,
    }

    # ensure name do not exceed 255 characters
    utils.check_string_length(name, 'name', min_length=1, max_length=255)

    # ensure name does not contain any special characters
    invalid_name = INVALID_NAME_REGEX.search(name)
    if invalid_name:
        msg = _("names can only contain [a-zA-Z0-9_.- ]")
        raise exception.InvalidInput(reason=msg)

    # Some attributes are positive ( > 0) integers
    for option in ['memory_mb', 'vcpus']:
        try:
            if int(str(kwargs[option])) <= 0:
                raise ValueError()
            kwargs[option] = int(kwargs[option])
        except (ValueError, TypeError):
            msg = _("'%s' argument must be a positive integer") % option
            raise exception.InvalidInput(reason=msg)

    # Some attributes are non-negative ( >= 0) integers
    for option in ['root_gb', 'ephemeral_gb', 'swap']:
        try:
            if int(str(kwargs[option])) < 0:
                raise ValueError()
            kwargs[option] = int(kwargs[option])
        except (ValueError, TypeError):
            msg = _("'%s' argument must be an integer greater than or"
                    " equal to 0") % option
            raise exception.InvalidInput(reason=msg)

    # rxtx_factor should be a positive float
    try:
        kwargs['rxtx_factor'] = float(kwargs['rxtx_factor'])
        if kwargs['rxtx_factor'] <= 0:
            raise ValueError()
    except ValueError:
        msg = _("'rxtx_factor' argument must be a positive float")
        raise exception.InvalidInput(reason=msg)

    kwargs['name'] = name
    # NOTE(vish): Internally, flavorid is stored as a string but it comes
    #             in through json as an integer, so we convert it here.
    kwargs['flavorid'] = unicode(flavorid)

    # ensure is_public attribute is boolean
    try:
        kwargs['is_public'] = strutils.bool_from_string(is_public, strict=True)
    except ValueError:
        raise exception.InvalidInput(reason=_("is_public must be a boolean"))

    try:
        return db.flavor_create(context.get_admin_context(), kwargs)
    except db_exc.DBError as e:
        LOG.exception(_('DB error: %s') % e)
        raise exception.InstanceTypeCreateFailed()
예제 #18
0
def create(name, memory, vcpus, root_gb, ephemeral_gb=0, flavorid=None,
           swap=0, rxtx_factor=1.0, is_public=True):
    """Creates flavors."""
    if not flavorid:
        flavorid = uuid.uuid4()

    kwargs = {
        'memory_mb': memory,
        'vcpus': vcpus,
        'root_gb': root_gb,
        'ephemeral_gb': ephemeral_gb,
        'swap': swap,
        'rxtx_factor': rxtx_factor,
    }

    if isinstance(name, six.string_types):
        name = name.strip()
    # ensure name do not exceed 255 characters
    utils.check_string_length(name, 'name', min_length=1, max_length=255)

    # ensure name does not contain any special characters
    valid_name = VALID_NAME_REGEX.search(name)
    if not valid_name:
        msg = _("Flavor names can only contain alphanumeric characters, "
                "periods, dashes, underscores and spaces.")
        raise exception.InvalidInput(reason=msg)

    # NOTE(vish): Internally, flavorid is stored as a string but it comes
    #             in through json as an integer, so we convert it here.
    flavorid = unicode(flavorid)

    # ensure leading/trailing whitespaces not present.
    if flavorid.strip() != flavorid:
        msg = _("id cannot contain leading and/or trailing whitespace(s)")
        raise exception.InvalidInput(reason=msg)

    # ensure flavor id does not exceed 255 characters
    utils.check_string_length(flavorid, 'id', min_length=1,
                              max_length=255)

    # ensure flavor id does not contain any special characters
    valid_flavor_id = VALID_ID_REGEX.search(flavorid)
    if not valid_flavor_id:
        msg = _("Flavor id can only contain letters from A-Z (both cases), "
                "periods, dashes, underscores and spaces.")
        raise exception.InvalidInput(reason=msg)

    # NOTE(wangbo): validate attributes of the creating flavor.
    # ram and vcpus should be positive ( > 0) integers.
    # disk, ephemeral and swap should be non-negative ( >= 0) integers.
    flavor_attributes = {
        'memory_mb': ('ram', 1),
        'vcpus': ('vcpus', 1),
        'root_gb': ('disk', 0),
        'ephemeral_gb': ('ephemeral', 0),
        'swap': ('swap', 0)
    }

    for key, value in flavor_attributes.items():
        kwargs[key] = utils.validate_integer(kwargs[key], value[0], value[1],
                                             db.MAX_INT)

    # rxtx_factor should be a positive float
    try:
        kwargs['rxtx_factor'] = float(kwargs['rxtx_factor'])
        if (kwargs['rxtx_factor'] <= 0 or
                kwargs['rxtx_factor'] > SQL_SP_FLOAT_MAX):
            raise ValueError()
    except ValueError:
        msg = (_("'rxtx_factor' argument must be a float between 0 and %g") %
               SQL_SP_FLOAT_MAX)
        raise exception.InvalidInput(reason=msg)

    kwargs['name'] = name
    kwargs['flavorid'] = flavorid
    # ensure is_public attribute is boolean
    try:
        kwargs['is_public'] = strutils.bool_from_string(
            is_public, strict=True)
    except ValueError:
        raise exception.InvalidInput(reason=_("is_public must be a boolean"))

    try:
        return db.flavor_create(context.get_admin_context(), kwargs)
    except db_exc.DBError as e:
        LOG.exception(_LE('DB error: %s'), e)
        raise exception.FlavorCreateFailed()
예제 #19
0
파일: flavors.py 프로젝트: polettix/nova
def create(name, memory, vcpus, root_gb, ephemeral_gb=0, flavorid=None,
           swap=0, rxtx_factor=1.0, is_public=True):
    """Creates flavors."""
    if not flavorid:
        flavorid = uuid.uuid4()

    kwargs = {
        'memory_mb': memory,
        'vcpus': vcpus,
        'root_gb': root_gb,
        'ephemeral_gb': ephemeral_gb,
        'swap': swap,
        'rxtx_factor': rxtx_factor,
    }

    # ensure name do not exceed 255 characters
    utils.check_string_length(name, 'name', min_length=1, max_length=255)

    # ensure name does not contain any special characters
    invalid_name = INVALID_NAME_REGEX.search(name)
    if invalid_name:
        msg = _("names can only contain [a-zA-Z0-9_.- ]")
        raise exception.InvalidInput(reason=msg)

    # Some attributes are positive ( > 0) integers
    for option in ['memory_mb', 'vcpus']:
        try:
            if int(str(kwargs[option])) <= 0:
                raise ValueError()
            kwargs[option] = int(kwargs[option])
        except (ValueError, TypeError):
            msg = _("'%s' argument must be a positive integer") % option
            raise exception.InvalidInput(reason=msg)

    # Some attributes are non-negative ( >= 0) integers
    for option in ['root_gb', 'ephemeral_gb', 'swap']:
        try:
            if int(str(kwargs[option])) < 0:
                raise ValueError()
            kwargs[option] = int(kwargs[option])
        except (ValueError, TypeError):
            msg = _("'%s' argument must be an integer greater than or"
                    " equal to 0") % option
            raise exception.InvalidInput(reason=msg)

    # rxtx_factor should be a positive float
    try:
        kwargs['rxtx_factor'] = float(kwargs['rxtx_factor'])
        if kwargs['rxtx_factor'] <= 0:
            raise ValueError()
    except ValueError:
        msg = _("'rxtx_factor' argument must be a positive float")
        raise exception.InvalidInput(reason=msg)

    kwargs['name'] = name
    # NOTE(vish): Internally, flavorid is stored as a string but it comes
    #             in through json as an integer, so we convert it here.
    kwargs['flavorid'] = unicode(flavorid)

    # ensure is_public attribute is boolean
    try:
        kwargs['is_public'] = strutils.bool_from_string(
            is_public, strict=True)
    except ValueError:
        raise exception.InvalidInput(reason=_("is_public must be a boolean"))

    try:
        return db.flavor_create(context.get_admin_context(), kwargs)
    except db_exc.DBError as e:
        LOG.exception(_('DB error: %s') % e)
        raise exception.InstanceTypeCreateFailed()