コード例 #1
0
ファイル: quotas.py プロジェクト: Juniper/nova
 def update_limit(cls, context, project_id, resource, limit, user_id=None):
     try:
         cls._update_limit_in_db(context, project_id, resource, limit,
                                 user_id=user_id)
     except exception.QuotaNotFound:
         db.quota_update(context, project_id, resource, limit,
                         user_id=user_id)
コード例 #2
0
ファイル: manage.py プロジェクト: comstud/nova
    def quota(self, project_id, key=None, value=None):
        """
        Create, update or display quotas for project

        If no quota key is provided, the quota will be displayed.
        If a valid quota key is provided and it does not exist,
        it will be created. Otherwise, it will be updated.
        """

        ctxt = context.get_admin_context()
        project_quota = QUOTAS.get_project_quotas(ctxt, project_id)
        # if key is None, that means we need to show the quotas instead
        # of updating them
        if key:
            if key in project_quota:
                if value.lower() == "unlimited":
                    value = -1
                try:
                    db.quota_update(ctxt, project_id, key, value)
                except exception.ProjectQuotaNotFound:
                    db.quota_create(ctxt, project_id, key, value)
            else:
                print _("%(key)s is not a valid quota key. Valid options are: " "%(options)s.") % {
                    "key": key,
                    "options": ", ".join(project_quota),
                }
                return 2
        print_format = "%-36s %-10s %-10s %-10s"
        print print_format % (_("Quota"), _("Limit"), _("In Use"), _("Reserved"))
        # Retrieve the quota after update
        project_quota = QUOTAS.get_project_quotas(ctxt, project_id)
        for key, value in project_quota.iteritems():
            if value["limit"] < 0 or value["limit"] is None:
                value["limit"] = "unlimited"
            print print_format % (key, value["limit"], value["in_use"], value["reserved"])
コード例 #3
0
ファイル: test_quota.py プロジェクト: yosh/nova
    def test_quota_overrides(self):
        """Make sure overriding a projects quotas works"""
        num_instances = quota.allowed_instances(self.context, 100,
            self._get_instance_type('m1.small'))
        self.assertEqual(num_instances, 2)
        db.quota_create(self.context, {'project_id': self.project.id,
                                       'instances': 10})
        num_instances = quota.allowed_instances(self.context, 100,
            self._get_instance_type('m1.small'))
        self.assertEqual(num_instances, 4)
        db.quota_update(self.context, self.project.id, {'cores': 100})
        num_instances = quota.allowed_instances(self.context, 100,
            self._get_instance_type('m1.small'))
        self.assertEqual(num_instances, 10)

        # metadata_items
        too_many_items = FLAGS.quota_metadata_items + 1000
        num_metadata_items = quota.allowed_metadata_items(self.context,
                                                          too_many_items)
        self.assertEqual(num_metadata_items, FLAGS.quota_metadata_items)
        db.quota_update(self.context, self.project.id, {'metadata_items': 5})
        num_metadata_items = quota.allowed_metadata_items(self.context,
                                                          too_many_items)
        self.assertEqual(num_metadata_items, 5)

        # Cleanup
        db.quota_destroy(self.context, self.project.id)
コード例 #4
0
ファイル: quotas.py プロジェクト: JacobMulero/nova
    def update(self, req, id, body):
        context = req.environ['nova.context']
        authorize_update(context)
        project_id = id

        bad_keys = []
        for key in body['quota_set'].keys():
            if (key not in QUOTAS and
                    key != 'tenant_id' and
                    key != 'id'):
                bad_keys.append(key)

        if len(bad_keys) > 0:
            msg = _("Bad key(s) %s in quota_set") % ",".join(bad_keys)
            raise webob.exc.HTTPBadRequest(explanation=msg)

        for key in body['quota_set'].keys():
            try:
                value = int(body['quota_set'][key])
            except (ValueError, TypeError):
                LOG.warn(_("Quota for %s should be integer.") % key)
                # NOTE(hzzhoushaoyu): Do not prevent valid value to be
                # updated. If raise BadRequest, some may be updated and
                # others may be not.
                continue
            self._validate_quota_limit(value)
            try:
                db.quota_update(context, project_id, key, value)
            except exception.ProjectQuotaNotFound:
                db.quota_create(context, project_id, key, value)
            except exception.AdminRequired:
                raise webob.exc.HTTPForbidden()
        return {'quota_set': self._get_quotas(context, id)}
コード例 #5
0
ファイル: quotas.py プロジェクト: Razique/nova
 def update(self, req, id, body):
     context = req.environ['nova.context']
     project_id = id
     for key in body['quota_set'].keys():
         if key in quota_resources:
             value = int(body['quota_set'][key])
             try:
                 db.quota_update(context, project_id, key, value)
             except exception.ProjectQuotaNotFound:
                 db.quota_create(context, project_id, key, value)
             except exception.AdminRequired:
                 raise webob.exc.HTTPForbidden()
     return {'quota_set': quota.get_project_quotas(context, project_id)}
コード例 #6
0
ファイル: test_quota.py プロジェクト: anotherjesse/nova
 def test_quota_overrides(self):
     """Make sure overriding a projects quotas works"""
     num_instances = quota.allowed_instances(self.context, 100,
         instance_types.INSTANCE_TYPES['m1.small'])
     self.assertEqual(num_instances, 2)
     db.quota_create(self.context, {'project_id': self.project.id,
                                    'instances': 10})
     num_instances = quota.allowed_instances(self.context, 100,
         instance_types.INSTANCE_TYPES['m1.small'])
     self.assertEqual(num_instances, 4)
     db.quota_update(self.context, self.project.id, {'cores': 100})
     num_instances = quota.allowed_instances(self.context, 100,
         instance_types.INSTANCE_TYPES['m1.small'])
     self.assertEqual(num_instances, 10)
     db.quota_destroy(self.context, self.project.id)
コード例 #7
0
ファイル: quotas.py プロジェクト: DSpeichert/nova
 def update(self, req, id, body):
     context = req.environ['nova.context']
     authorize_update(context)
     project_id = id
     for key in body['quota_set'].keys():
         if key in QUOTAS:
             value = int(body['quota_set'][key])
             self._validate_quota_limit(value)
             try:
                 db.quota_update(context, project_id, key, value)
             except exception.ProjectQuotaNotFound:
                 db.quota_create(context, project_id, key, value)
             except exception.AdminRequired:
                 raise webob.exc.HTTPForbidden()
     return {'quota_set': self._get_quotas(context, id)}
コード例 #8
0
 def update(self, req, id, body):
     context = req.environ['nova.context']
     authorize(context)
     project_id = id
     for key in body['quota_set'].keys():
         if key in quota.quota_resources:
             value = int(body['quota_set'][key])
             self._validate_quota_limit(value)
             try:
                 db.quota_update(context, project_id, key, value)
             except exception.ProjectQuotaNotFound:
                 db.quota_create(context, project_id, key, value)
             except exception.AdminRequired:
                 raise webob.exc.HTTPForbidden()
     return {'quota_set': quota.get_project_quotas(context, project_id)}
コード例 #9
0
ファイル: admin.py プロジェクト: mgius/openstackx
    def update(self, req, id, body):
        context = req.environ['nova.context']
        project_id = id
        resources = ['metadata_items', 'injected_file_content_bytes',
                'volumes', 'gigabytes', 'ram', 'floating_ips', 'instances',
                'injected_files', 'cores']

        for key in body['quota_set'].keys():
            if key in resources:
                value = int(body['quota_set'][key])
                try:
                    db.quota_update(context, project_id, key, value)
                except exception.ProjectQuotaNotFound:
                    db.quota_create(context, project_id, key, value)
        return {'quota_set': quota.get_project_quotas(context, project_id)}
コード例 #10
0
    def update(self, req, id, body):
        context = req.environ['nova.context']
        project_id = id
        resources = [
            'metadata_items', 'injected_file_content_bytes', 'volumes',
            'gigabytes', 'ram', 'floating_ips', 'instances', 'injected_files',
            'cores'
        ]

        for key in body['quota_set'].keys():
            if key in resources:
                value = int(body['quota_set'][key])
                try:
                    db.quota_update(context, project_id, key, value)
                except exception.ProjectQuotaNotFound:
                    db.quota_create(context, project_id, key, value)
        return {'quota_set': quota.get_project_quotas(context, project_id)}
コード例 #11
0
ファイル: quotas.py プロジェクト: StackOps/nova
 def update(self, req, id, body):
     context = req.environ['nova.context']
     authorize_update(context)
     project_id = id
     for key in body['quota_set'].keys():
         if key in QUOTAS:
             try:
                 value = int(body['quota_set'][key])
             except (ValueError, TypeError):
                 LOG.warn(_("Quota for %s should be integer.") % key)
                 # NOTE(hzzhoushaoyu): Do not prevent valid value to be
                 # updated. If raise BadRequest, some may be updated and
                 # others may be not.
                 continue
             self._validate_quota_limit(value)
             try:
                 db.quota_update(context, project_id, key, value)
             except exception.ProjectQuotaNotFound:
                 db.quota_create(context, project_id, key, value)
             except exception.AdminRequired:
                 raise webob.exc.HTTPForbidden()
     return {'quota_set': self._get_quotas(context, id)}
コード例 #12
0
    def quota(self, project_id, key=None, value=None):
        """
        Create, update or display quotas for project

        If no quota key is provided, the quota will be displayed.
        If a valid quota key is provided and it does not exist,
        it will be created. Otherwise, it will be updated.
        """

        ctxt = context.get_admin_context()
        project_quota = QUOTAS.get_project_quotas(ctxt, project_id)
        # if key is None, that means we need to show the quotas instead
        # of updating them
        if key:
            if key in project_quota:
                if value.lower() == 'unlimited':
                    value = -1
                try:
                    db.quota_update(ctxt, project_id, key, value)
                except exception.ProjectQuotaNotFound:
                    db.quota_create(ctxt, project_id, key, value)
            else:
                print _('%(key)s is not a valid quota key. Valid options are: '
                        '%(options)s.') % {'key': key,
                                           'options': ', '.join(project_quota)}
                return(2)
        print_format = "%-36s %-10s %-10s %-10s"
        print print_format % (
                    _('Quota'),
                    _('Limit'),
                    _('In Use'),
                    _('Reserved'))
        # Retrieve the quota after update
        project_quota = QUOTAS.get_project_quotas(ctxt, project_id)
        for key, value in project_quota.iteritems():
            if value['limit'] < 0 or value['limit'] is None:
                value['limit'] = 'unlimited'
            print print_format % (key, value['limit'], value['in_use'],
                                  value['reserved'])
コード例 #13
0
 def update(self, req, id, body):
     context = req.environ['nova.context']
     authorize_update(context)
     project_id = id
     for key in body['quota_set'].keys():
         if key in QUOTAS:
             try:
                 value = int(body['quota_set'][key])
             except (ValueError, TypeError):
                 LOG.warn(_("Quota for %s should be integer.") % key)
                 # NOTE(hzzhoushaoyu): Do not prevent valid value to be
                 # updated. If raise BadRequest, some may be updated and
                 # others may be not.
                 continue
             self._validate_quota_limit(value)
             try:
                 db.quota_update(context, project_id, key, value)
             except exception.ProjectQuotaNotFound:
                 db.quota_create(context, project_id, key, value)
             except exception.AdminRequired:
                 raise webob.exc.HTTPForbidden()
     return {'quota_set': self._get_quotas(context, id)}
コード例 #14
0
ファイル: quotas.py プロジェクト: bhuvan/nova
    def update(self, req, id, body):
        context = req.environ['nova.context']
        params = self._request_params(req)
        project_id = id
        user_id = None
        remains = {}
        quotas = {}
        if 'user_id' in params:
            # Project admins are able to modify per-user quotas.
            authorize_action(context, 'update_for_user')
            user_id = params["user_id"][0]
            remains = self._get_quotas(context, project_id, remaining=True)
            quotas = db.quota_get_all_by_user(context, user_id, project_id)
        else:
            # Only admins are able to modify per-project quotas.
            authorize_action(context, 'update_for_project')

        for key in body['quota_set'].keys():
            if key in QUOTAS:
                value = int(body['quota_set'][key])
                try:
                    if user_id:
                        self._validate_quota_limit(value, remains.get(key, 0),
                                                   quotas.get(key, 0))
                        db.quota_update_for_user(context, user_id,
                                                 project_id, key, value)
                    else:
                        self._validate_quota_limit(value, remains.get(key, -1),
                                                   quotas.get(key, 0))
                        db.quota_update(context, project_id, key, value)
                except exception.ProjectQuotaNotFound:
                    db.quota_create(context, project_id, key, value)
                except exception.UserQuotaNotFound:
                    db.quota_create_for_user(context, user_id,
                                             project_id, key, value)
                except exception.AdminRequired:
                    raise webob.exc.HTTPForbidden()
        return {'quota_set': self._get_quotas(context, id, user_id)}
コード例 #15
0
    def update(self, req, id, body):
        context = req.environ['nova.context']
        params = self._request_params(req)
        project_id = id
        user_id = None
        remains = {}
        quotas = {}
        if 'user_id' in params:
            # Project admins are able to modify per-user quotas.
            authorize_action(context, 'update_for_user')
            user_id = params["user_id"][0]
            remains = self._get_quotas(context, project_id, remaining=True)
            quotas = db.quota_get_all_by_user(context, user_id, project_id)
        else:
            # Only admins are able to modify per-project quotas.
            authorize_action(context, 'update_for_project')

        for key in body['quota_set'].keys():
            if key in QUOTAS:
                value = int(body['quota_set'][key])
                try:
                    if user_id:
                        self._validate_quota_limit(value, remains.get(key, 0),
                                                   quotas.get(key, 0))
                        db.quota_update_for_user(context, user_id, project_id,
                                                 key, value)
                    else:
                        self._validate_quota_limit(value, remains.get(key, -1),
                                                   quotas.get(key, 0))
                        db.quota_update(context, project_id, key, value)
                except exception.ProjectQuotaNotFound:
                    db.quota_create(context, project_id, key, value)
                except exception.UserQuotaNotFound:
                    db.quota_create_for_user(context, user_id, project_id, key,
                                             value)
                except exception.AdminRequired:
                    raise webob.exc.HTTPForbidden()
        return {'quota_set': self._get_quotas(context, id, user_id)}
コード例 #16
0
ファイル: admin.py プロジェクト: gandelman-a/openstackx
    def update(self, req, id, body):
        context = req.environ["nova.context"]
        project_id = id
        resources = [
            "metadata_items",
            "injected_file_content_bytes",
            "volumes",
            "gigabytes",
            "ram",
            "floating_ips",
            "instances",
            "injected_files",
            "cores",
        ]

        for key in body["quota_set"].keys():
            if key in resources:
                value = int(body["quota_set"][key])
                try:
                    db.quota_update(context, project_id, key, value)
                except exception.ProjectQuotaNotFound:
                    db.quota_create(context, project_id, key, value)
        return {"quota_set": quota.get_project_quotas(context, project_id)}
コード例 #17
0
    def update(self, req, id, body):
        context = req.environ['nova.context']
        authorize_update(context)
        params = urlparse.parse_qs(req.environ.get('QUERY_STRING', ''))
        project_id = params.get('project_id', [None])[0]
        user_id = params.get('user_id', [None])[0]
        
        bad_keys = []
        try:
            if (user_id == None) and (project_id == None):
                 nova.context.authorize_domain_context(context, id)
                 settable_quotas = QUOTAS.get_settable_quotas_for_domain(context, id)
            elif user_id:
                 nova.context.authorize_project_user_context(context, project_id, user_id)
                 settable_quotas = QUOTAS.get_settable_quotas_for_domain(context, id, project_id=project_id, user_id=user_id)
                 LOG.debug(_("Inside the User Quota %(key)s used: "), {'key': settable_quotas})
                 if len(settable_quotas) <= 1:
                     ## because settable_quotas dict may have project_id as one key
                     raise webob.exc.HTTPBadRequest(explanation='The quotas for the project are not set. So, first define the quotas for the project')
            else:
                 nova.context.authorize_domain_project_context(context, id, project_id)
                 settable_quotas = QUOTAS.get_settable_quotas_for_domain(context, id, project_id=project_id)
                 LOG.debug(_("Inside the Project Quota %(key)s used: "), {'key': settable_quotas})
                 if len(settable_quotas) <= 1:
                     ## because settable_quotas dict may have domain_id as one key
                     raise webob.exc.HTTPBadRequest(explanation='The quotas for the domain of this project are not set. So, first define the quotas for the domain')

        except exception.NotAuthorized:
            raise webob.exc.HTTPForbidden()

        if not self.is_valid_body(body, 'quota_set'):
            msg = _("quota_set not specified")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        quota_set = body['quota_set']
        parNode_notFoundKeys = []
        if 'notfound_keys' in settable_quotas:
            parNode_notFoundKeys = settable_quotas['notfound_keys']
        for key, value in quota_set.items():
            if (key not in QUOTAS and
                    key not in NON_QUOTA_KEYS):
                bad_keys.append(key)
                continue

            if key in parNode_notFoundKeys:
                excepMessage = 'The quota value for resource ' + key + ' is not defined for the parent'
                raise webob.exc.HTTPBadRequest(explanation=excepMessage)

            if key not in NON_QUOTA_KEYS and value:
                try:
                    value = utils.validate_integer(value, key)
                except exception.InvalidInput as e:
                    LOG.warn(e.format_message())
                    raise webob.exc.HTTPBadRequest(
                        explanation=e.format_message())

        if len(bad_keys) > 0:
            msg = _("Bad key(s) %s in quota_set") % ",".join(bad_keys)
            raise webob.exc.HTTPBadRequest(explanation=msg)

        LOG.debug(_("Quota %(key)s used: "),
                              {'key': settable_quotas})

        for key, value in quota_set.items():
            if key in NON_QUOTA_KEYS or (not value and value != 0):
                continue
            value = int(value)
            if value >= 0:
                quota_value = settable_quotas.get(key)
                if quota_value and quota_value['limit'] >= 0:
                    quota_used = (quota_value['in_use'] +
                                  quota_value['reserved'])
                    LOG.debug(_("Quota %(key)s used: %(quota_used)s, "
                                "value: %(value)s."),
                              {'key': key, 'quota_used': quota_used,
                               'value': value})
                    if quota_used > value:
                        msg = (_("Quota value %(value)s for %(key)s are "
                                "less than already used and reserved "
                                "%(quota_used)s") %
                                {'value': value, 'key': key,
                                 'quota_used': quota_used})
                        raise webob.exc.HTTPBadRequest(explanation=msg)

            minimum = settable_quotas[key]['minimum']
            maximum = settable_quotas[key]['maximum']
            self._validate_quota_limit(key, value, minimum, maximum)
            try:
                if (user_id == None) and (project_id == None):
                    db.domain_quota_create(context, id, key, value)
                else:
                    db.quota_create(context, project_id, key, value,
                                user_id=user_id)
            except exception.DomainQuotaExists:
                db.domain_quota_update(context, id, key, value)
            except exception.QuotaExists:
                db.quota_update(context, project_id, key, value, user_id=user_id)
            except exception.AdminRequired:
                raise webob.exc.HTTPForbidden()
        return {'quota_set': self._get_quotas(context, id, user_id=user_id, project_id=project_id)}
コード例 #18
0
ファイル: quotas.py プロジェクト: liunian0o0/nova-1
 def update_limit(cls, context, project_id, resource, limit, user_id=None):
     # NOTE(danms,comstud): Quotas likely needs an overhaul and currently
     # doesn't map very well to objects. Since there is quite a bit of
     # logic in the db api layer for this, just pass this through for now.
     db.quota_update(context, project_id, resource, limit, user_id=user_id)
コード例 #19
0
ファイル: quota_sets.py プロジェクト: B-Rich/nova-1
    def update(self, req, id, body):
        context = req.environ['nova.context']
        authorize_update(context)
        project_id = id
        params = urlparse.parse_qs(req.environ.get('QUERY_STRING', ''))
        user_id = params.get('user_id', [None])[0]

        bad_keys = []
        force_update = False

        if not self.is_valid_body(body, 'quota_set'):
            msg = _("quota_set not specified")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        quota_set = body['quota_set']

        for key, value in quota_set.items():
            if ((key not in QUOTAS or key in FILTERED_QUOTAS)
                 and key != 'force'):
                bad_keys.append(key)
                continue
            if key == 'force':
                force_update = strutils.bool_from_string(value)
            elif key != 'force' and value:
                try:
                    value = utils.validate_integer(
                        value, key)
                except exception.InvalidInput as e:
                    LOG.warn(e.format_message())
                    raise webob.exc.HTTPBadRequest(
                        explanation=e.format_message())

        if len(bad_keys) > 0:
            msg = _("Bad key(s) %s in quota_set") % ",".join(bad_keys)
            raise webob.exc.HTTPBadRequest(explanation=msg)

        try:
            settable_quotas = QUOTAS.get_settable_quotas(context, project_id,
                                                         user_id=user_id)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()

        try:
            quotas = self._get_quotas(context, id, user_id=user_id,
                                      usages=True)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()

        LOG.debug("Force update quotas: %s", force_update)

        for key, value in body['quota_set'].iteritems():
            if key == 'force' or (not value and value != 0):
                continue
            # validate whether already used and reserved exceeds the new
            # quota, this check will be ignored if admin want to force
            # update
            value = int(value)
            if force_update is not True and value >= 0:
                quota_value = quotas.get(key)
                if quota_value and quota_value['limit'] >= 0:
                    quota_used = (quota_value['in_use'] +
                                  quota_value['reserved'])
                    LOG.debug("Quota %(key)s used: %(quota_used)s, "
                              "value: %(value)s.",
                              {'key': key, 'quota_used': quota_used,
                               'value': value})
                    if quota_used > value:
                        msg = (_("Quota value %(value)s for %(key)s are "
                                "less than already used and reserved "
                                "%(quota_used)s") %
                                {'value': value, 'key': key,
                                 'quota_used': quota_used})
                        raise webob.exc.HTTPBadRequest(explanation=msg)

            minimum = settable_quotas[key]['minimum']
            maximum = settable_quotas[key]['maximum']
            self._validate_quota_limit(value, minimum, maximum)
            try:
                db.quota_create(context, project_id, key, value,
                                user_id=user_id)
            except exception.QuotaExists:
                db.quota_update(context, project_id, key, value,
                                user_id=user_id)
            except exception.AdminRequired:
                raise webob.exc.HTTPForbidden()
        return self._format_quota_set(id, self._get_quotas(context, id,
                                                           user_id=user_id))
コード例 #20
0
    def update(self, req, id, body):
        context = req.environ['nova.context']
        authorize_update(context)
        project_id = id
        params = urlparse.parse_qs(req.environ.get('QUERY_STRING', ''))
        user_id = params.get('user_id', [None])[0]

        bad_keys = []
        force_update = False

        if not self.is_valid_body(body, 'quota_set'):
            msg = _("quota_set not specified")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        quota_set = body['quota_set']

        for key, value in quota_set.items():
            if key not in QUOTAS and key != 'force':
                bad_keys.append(key)
                continue
            if key == 'force':
                force_update = strutils.bool_from_string(value)
            elif key != 'force' and value:
                try:
                    value = int(value)
                except (ValueError, TypeError):
                    msg = _("Quota value for key '%(key)s' should be an "
                            "integer.  It is actually type '%(vtype)s'.")
                    msg = msg % {'key': key, 'vtype': type(value)}
                    LOG.warn(msg)
                    raise webob.exc.HTTPBadRequest(explanation=msg)

        if len(bad_keys) > 0:
            msg = _("Bad key(s) %s in quota_set") % ",".join(bad_keys)
            raise webob.exc.HTTPBadRequest(explanation=msg)

        try:
            settable_quotas = QUOTAS.get_settable_quotas(context,
                                                         project_id,
                                                         user_id=user_id)
        except exception.NotAuthorized:
            raise webob.exc.HTTPForbidden()

        try:
            quotas = self._get_quotas(context,
                                      id,
                                      user_id=user_id,
                                      usages=True)
        except exception.NotAuthorized:
            raise webob.exc.HTTPForbidden()

        LOG.debug(_("Force update quotas: %s"), force_update)

        for key, value in body['quota_set'].iteritems():
            if key == 'force' or (not value and value != 0):
                continue
            # validate whether already used and reserved exceeds the new
            # quota, this check will be ignored if admin want to force
            # update
            value = int(value)
            if force_update is not True and value >= 0:
                quota_value = quotas.get(key)
                if quota_value and quota_value['limit'] >= 0:
                    quota_used = (quota_value['in_use'] +
                                  quota_value['reserved'])
                    LOG.debug(
                        _("Quota %(key)s used: %(quota_used)s, "
                          "value: %(value)s."), {
                              'key': key,
                              'quota_used': quota_used,
                              'value': value
                          })
                    if quota_used > value:
                        msg = (_("Quota value %(value)s for %(key)s are "
                                 "less than already used and reserved "
                                 "%(quota_used)s") % {
                                     'value': value,
                                     'key': key,
                                     'quota_used': quota_used
                                 })
                        raise webob.exc.HTTPBadRequest(explanation=msg)

            minimum = settable_quotas[key]['minimum']
            maximum = settable_quotas[key]['maximum']
            self._validate_quota_limit(value, minimum, maximum)
            try:
                db.quota_create(context,
                                project_id,
                                key,
                                value,
                                user_id=user_id)
            except exception.QuotaExists:
                db.quota_update(context,
                                project_id,
                                key,
                                value,
                                user_id=user_id)
            except exception.AdminRequired:
                raise webob.exc.HTTPForbidden()
        return self._format_quota_set(
            id, self._get_quotas(context, id, user_id=user_id))
コード例 #21
0
ファイル: quotas.py プロジェクト: jevonyeoh/nova-simulator
    def update(self, req, id, body):
        context = req.environ["nova.context"]
        authorize_update(context)
        project_id = id

        bad_keys = []

        # By default, we can force update the quota if the extended
        # is not loaded
        force_update = True
        extended_loaded = False
        if self.ext_mgr.is_loaded("os-extended-quotas"):
            # force optional has been enabled, the default value of
            # force_update need to be changed to False
            extended_loaded = True
            force_update = False

        user_id = None
        if self.ext_mgr.is_loaded("os-user-quotas"):
            # Update user quotas only if the extended is loaded
            params = urlparse.parse_qs(req.environ.get("QUERY_STRING", ""))
            user_id = params.get("user_id", [None])[0]

        try:
            settable_quotas = QUOTAS.get_settable_quotas(context, project_id, user_id=user_id)
        except exception.NotAuthorized:
            raise webob.exc.HTTPForbidden()

        if not self.is_valid_body(body, "quota_set"):
            msg = _("quota_set not specified")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        quota_set = body["quota_set"]
        for key, value in quota_set.items():
            if key not in QUOTAS and key not in NON_QUOTA_KEYS:
                bad_keys.append(key)
                continue
            if key == "force" and extended_loaded:
                # only check the force optional when the extended has
                # been loaded
                force_update = strutils.bool_from_string(value)
            elif key not in NON_QUOTA_KEYS and value:
                try:
                    value = utils.validate_integer(value, key)
                except exception.InvalidInput as e:
                    LOG.warn(e.format_message())
                    raise webob.exc.HTTPBadRequest(explanation=e.format_message())

        LOG.debug(_("force update quotas: %s") % force_update)

        if len(bad_keys) > 0:
            msg = _("Bad key(s) %s in quota_set") % ",".join(bad_keys)
            raise webob.exc.HTTPBadRequest(explanation=msg)

        try:
            quotas = self._get_quotas(context, id, user_id=user_id, usages=True)
        except exception.NotAuthorized:
            raise webob.exc.HTTPForbidden()

        for key, value in quota_set.items():
            if key in NON_QUOTA_KEYS or (not value and value != 0):
                continue
            # validate whether already used and reserved exceeds the new
            # quota, this check will be ignored if admin want to force
            # update
            value = int(value)
            if force_update is not True and value >= 0:
                quota_value = quotas.get(key)
                if quota_value and quota_value["limit"] >= 0:
                    quota_used = quota_value["in_use"] + quota_value["reserved"]
                    LOG.debug(
                        _("Quota %(key)s used: %(quota_used)s, " "value: %(value)s."),
                        {"key": key, "quota_used": quota_used, "value": value},
                    )
                    if quota_used > value:
                        msg = _(
                            "Quota value %(value)s for %(key)s are "
                            "less than already used and reserved "
                            "%(quota_used)s"
                        ) % {"value": value, "key": key, "quota_used": quota_used}
                        raise webob.exc.HTTPBadRequest(explanation=msg)

            minimum = settable_quotas[key]["minimum"]
            maximum = settable_quotas[key]["maximum"]
            self._validate_quota_limit(value, minimum, maximum)
            try:
                db.quota_create(context, project_id, key, value, user_id=user_id)
            except exception.QuotaExists:
                db.quota_update(context, project_id, key, value, user_id=user_id)
            except exception.AdminRequired:
                raise webob.exc.HTTPForbidden()
        return {"quota_set": self._get_quotas(context, id, user_id=user_id)}
コード例 #22
0
    def update(self, req, id, body):
        context = req.environ['nova.context']
        authorize_update(context)
        project_id = id
        params = urlparse.parse_qs(req.environ.get('QUERY_STRING', ''))
        user_id = params.get('user_id', [None])[0]

        quota_set = body['quota_set']
        force_update = strutils.bool_from_string(
            quota_set.get('force', 'False'))

        try:
            settable_quotas = QUOTAS.get_settable_quotas(context,
                                                         project_id,
                                                         user_id=user_id)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()

        try:
            quotas = self._get_quotas(context,
                                      id,
                                      user_id=user_id,
                                      usages=True)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()

        LOG.debug("Force update quotas: %s", force_update)

        for key, value in body['quota_set'].iteritems():
            if key == 'force' or (not value and value != 0):
                continue
            # validate whether already used and reserved exceeds the new
            # quota, this check will be ignored if admin want to force
            # update
            value = int(value)
            if force_update is not True and value >= 0:
                quota_value = quotas.get(key)
                if quota_value and quota_value['limit'] >= 0:
                    quota_used = (quota_value['in_use'] +
                                  quota_value['reserved'])
                    LOG.debug(
                        "Quota %(key)s used: %(quota_used)s, "
                        "value: %(value)s.", {
                            'key': key,
                            'quota_used': quota_used,
                            'value': value
                        })
                    if quota_used > value:
                        msg = (_("Quota value %(value)s for %(key)s are "
                                 "less than already used and reserved "
                                 "%(quota_used)s") % {
                                     'value': value,
                                     'key': key,
                                     'quota_used': quota_used
                                 })
                        raise webob.exc.HTTPBadRequest(explanation=msg)

            minimum = settable_quotas[key]['minimum']
            maximum = settable_quotas[key]['maximum']
            self._validate_quota_limit(value, minimum, maximum)
            try:
                db.quota_create(context,
                                project_id,
                                key,
                                value,
                                user_id=user_id)
            except exception.QuotaExists:
                db.quota_update(context,
                                project_id,
                                key,
                                value,
                                user_id=user_id)
            except exception.AdminRequired:
                raise webob.exc.HTTPForbidden()
        return self._format_quota_set(
            id, self._get_quotas(context, id, user_id=user_id))
コード例 #23
0
ファイル: quota_sets.py プロジェクト: 674009287/nova
    def update(self, req, id, body):
        context = req.environ["nova.context"]
        authorize_update(context)
        project_id = id
        params = urlparse.parse_qs(req.environ.get("QUERY_STRING", ""))
        user_id = params.get("user_id", [None])[0]

        bad_keys = []
        force_update = False

        for key, value in body["quota_set"].items():
            if key not in QUOTAS and key != "force":
                bad_keys.append(key)
                continue
            if key == "force":
                force_update = strutils.bool_from_string(value)
            elif key != "force" and value:
                try:
                    value = int(value)
                except (ValueError, TypeError):
                    msg = _("Quota value for key '%(key)s' should be an " "integer.  It is actually type '%(vtype)s'.")
                    msg = msg % {"key": key, "vtype": type(value)}
                    LOG.warn(msg)
                    raise webob.exc.HTTPBadRequest(explanation=msg)

        if len(bad_keys) > 0:
            msg = _("Bad key(s) %s in quota_set") % ",".join(bad_keys)
            raise webob.exc.HTTPBadRequest(explanation=msg)

        try:
            settable_quotas = QUOTAS.get_settable_quotas(context, project_id, user_id=user_id)
        except exception.NotAuthorized:
            raise webob.exc.HTTPForbidden()

        try:
            quotas = self._get_quotas(context, id, user_id=user_id, usages=True)
        except exception.NotAuthorized:
            raise webob.exc.HTTPForbidden()

        LOG.debug(_("Force update quotas: %s"), force_update)

        for key, value in body["quota_set"].iteritems():
            if key == "force" or (not value and value != 0):
                continue
            # validate whether already used and reserved exceeds the new
            # quota, this check will be ignored if admin want to force
            # update
            value = int(value)
            if force_update is not True and value >= 0:
                quota_value = quotas.get(key)
                if quota_value and quota_value["limit"] >= 0:
                    quota_used = quota_value["in_use"] + quota_value["reserved"]
                    LOG.debug(
                        _("Quota %(key)s used: %(quota_used)s, " "value: %(value)s."),
                        {"key": key, "quota_used": quota_used, "value": value},
                    )
                    if quota_used > value:
                        msg = _(
                            "Quota value %(value)s for %(key)s are "
                            "less than already used and reserved "
                            "%(quota_used)s"
                        ) % {"value": value, "key": key, "quota_used": quota_used}
                        raise webob.exc.HTTPBadRequest(explanation=msg)

            minimum = settable_quotas[key]["minimum"]
            maximum = settable_quotas[key]["maximum"]
            self._validate_quota_limit(value, minimum, maximum)
            try:
                db.quota_create(context, project_id, key, value, user_id=user_id)
            except exception.QuotaExists:
                db.quota_update(context, project_id, key, value, user_id=user_id)
            except exception.AdminRequired:
                raise webob.exc.HTTPForbidden()
        return self._format_quota_set(id, self._get_quotas(context, id, user_id=user_id))
コード例 #24
0
ファイル: manage.py プロジェクト: RibeiroAna/nova
    def quota(self, project_id, user_id=None, key=None, value=None):
        """Create, update or display quotas for project/user

        If no quota key is provided, the quota will be displayed.
        If a valid quota key is provided and it does not exist,
        it will be created. Otherwise, it will be updated.
        """

        ctxt = context.get_admin_context()
        if user_id:
            quota = QUOTAS.get_user_quotas(ctxt, project_id, user_id)
        else:
            user_id = None
            quota = QUOTAS.get_project_quotas(ctxt, project_id)
        # if key is None, that means we need to show the quotas instead
        # of updating them
        if key:
            settable_quotas = QUOTAS.get_settable_quotas(ctxt,
                                                         project_id,
                                                         user_id=user_id)
            if key in quota:
                minimum = settable_quotas[key]['minimum']
                maximum = settable_quotas[key]['maximum']
                if value.lower() == 'unlimited':
                    value = -1
                if int(value) < -1:
                    print(_('Quota limit must be -1 or greater.'))
                    return(2)
                if ((int(value) < minimum) and
                   (maximum != -1 or (maximum == -1 and int(value) != -1))):
                    print(_('Quota limit must be greater than %s.') % minimum)
                    return(2)
                if maximum != -1 and int(value) > maximum:
                    print(_('Quota limit must be less than %s.') % maximum)
                    return(2)
                try:
                    db.quota_create(ctxt, project_id, key, value,
                                    user_id=user_id)
                except exception.QuotaExists:
                    db.quota_update(ctxt, project_id, key, value,
                                    user_id=user_id)
            else:
                print(_('%(key)s is not a valid quota key. Valid options are: '
                        '%(options)s.') % {'key': key,
                                           'options': ', '.join(quota)})
                return(2)
        print_format = "%-36s %-10s %-10s %-10s"
        print(print_format % (
                    _('Quota'),
                    _('Limit'),
                    _('In Use'),
                    _('Reserved')))
        # Retrieve the quota after update
        if user_id:
            quota = QUOTAS.get_user_quotas(ctxt, project_id, user_id)
        else:
            quota = QUOTAS.get_project_quotas(ctxt, project_id)
        for key, value in quota.iteritems():
            if value['limit'] < 0 or value['limit'] is None:
                value['limit'] = 'unlimited'
            print(print_format % (key, value['limit'], value['in_use'],
                                  value['reserved']))
コード例 #25
0
ファイル: quota_sets.py プロジェクト: elmarco/nova
    def update(self, req, id, body):
        context = req.environ['nova.context']
        authorize_update(context)
        project_id = id

        bad_keys = []
        force_update = False

        for key, value in body['quota_set'].items():
            if (key not in QUOTAS and
                    key not in NON_QUOTA_KEYS):
                bad_keys.append(key)
                continue
            if key == 'force':
                force_update = strutils.bool_from_string(value)
            elif key not in NON_QUOTA_KEYS and value:
                try:
                    value = int(value)
                except (ValueError, TypeError):
                    msg = _("Quota '%(value)s' for %(key)s should be "
                            "integer.") % {'value': value, 'key': key}
                    LOG.warn(msg)
                    raise webob.exc.HTTPBadRequest(explanation=msg)
                self._validate_quota_limit(value)

        LOG.debug(_("force update quotas: %s") % force_update)

        if len(bad_keys) > 0:
            msg = _("Bad key(s) %s in quota_set") % ",".join(bad_keys)
            raise webob.exc.HTTPBadRequest(explanation=msg)

        try:
            project_quota = self._get_quotas(context, id, True)
        except exception.NotAuthorized:
            raise webob.exc.HTTPForbidden()

        for key, value in body['quota_set'].items():
            if key in NON_QUOTA_KEYS or not value:
                continue
            # validate whether already used and reserved exceeds the new
            # quota, this check will be ignored if admin want to force
            # update
            value = int(value)
            if force_update is not True and value >= 0:
                quota_value = project_quota.get(key)
                if quota_value and quota_value['limit'] >= 0:
                    quota_used = (quota_value['in_use'] +
                                  quota_value['reserved'])
                    LOG.debug(_("Quota %(key)s used: %(quota_used)s, "
                                "value: %(value)s."),
                              {'key': key, 'quota_used': quota_used,
                               'value': value})
                    if quota_used > value:
                        msg = (_("Quota value %(value)s for %(key)s are "
                                "greater than already used and reserved "
                                "%(quota_used)s") %
                                {'value': value, 'key': key,
                                 'quota_used': quota_used})
                        raise webob.exc.HTTPBadRequest(explanation=msg)

            try:
                db.quota_update(context, project_id, key, value)
            except exception.ProjectQuotaNotFound:
                db.quota_create(context, project_id, key, value)
            except exception.AdminRequired:
                raise webob.exc.HTTPForbidden()
        return {'quota_set': self._get_quotas(context, id)}
コード例 #26
0
ファイル: quota_sets.py プロジェクト: scottchoi/nova
    def update(self, req, id, body):
        context = req.environ['nova.context']
        authorize_update(context)
        project_id = id

        bad_keys = []

        # By default, we can force update the quota if the extended
        # is not loaded
        force_update = True
        extended_loaded = False
        if self.ext_mgr.is_loaded('os-extended-quotas'):
            # force optional has been enabled, the default value of
            # force_update need to be changed to False
            extended_loaded = True
            force_update = False

        for key, value in body['quota_set'].items():
            if (key not in QUOTAS and key not in NON_QUOTA_KEYS):
                bad_keys.append(key)
                continue
            if key == 'force' and extended_loaded:
                # only check the force optional when the extended has
                # been loaded
                force_update = strutils.bool_from_string(value)
            elif key not in NON_QUOTA_KEYS and value:
                try:
                    value = int(value)
                except (ValueError, TypeError):
                    msg = _("Quota '%(value)s' for %(key)s should be "
                            "integer.") % locals()
                    LOG.warn(msg)
                    raise webob.exc.HTTPBadRequest(explanation=msg)
                self._validate_quota_limit(value)

        LOG.debug(_("force update quotas: %s") % force_update)

        if len(bad_keys) > 0:
            msg = _("Bad key(s) %s in quota_set") % ",".join(bad_keys)
            raise webob.exc.HTTPBadRequest(explanation=msg)

        try:
            project_quota = self._get_quotas(context, id, True)
        except exception.NotAuthorized:
            raise webob.exc.HTTPForbidden()

        for key, value in body['quota_set'].items():
            if key in NON_QUOTA_KEYS or not value:
                continue
            # validate whether already used and reserved exceeds the new
            # quota, this check will be ignored if admin want to force
            # update
            value = int(value)
            if force_update is not True and value >= 0:
                quota_value = project_quota.get(key)
                if quota_value and quota_value['limit'] >= 0:
                    quota_used = (quota_value['in_use'] +
                                  quota_value['reserved'])
                    LOG.debug(
                        _("Quota %(key)s used: %(quota_used)s, "
                          "value: %(value)s."), {
                              'key': key,
                              'quota_used': quota_used,
                              'value': value
                          })
                    if quota_used > value:
                        msg = (_("Quota value %(value)s for %(key)s are "
                                 "greater than already used and reserved "
                                 "%(quota_used)s") % {
                                     'value': value,
                                     'key': key,
                                     'quota_used': quota_used
                                 })
                        raise webob.exc.HTTPBadRequest(explanation=msg)

            try:
                db.quota_update(context, project_id, key, value)
            except exception.ProjectQuotaNotFound:
                db.quota_create(context, project_id, key, value)
            except exception.AdminRequired:
                raise webob.exc.HTTPForbidden()
        return {'quota_set': self._get_quotas(context, id)}
コード例 #27
0
ファイル: quotas.py プロジェクト: AsherBond/nova
 def update_limit(cls, context, project_id, resource, limit, user_id=None):
     # NOTE(danms,comstud): Quotas likely needs an overhaul and currently
     # doesn't map very well to objects. Since there is quite a bit of
     # logic in the db api layer for this, just pass this through for now.
     db.quota_update(context, project_id, resource, limit, user_id=user_id)
コード例 #28
0
ファイル: manage.py プロジェクト: mba811/nova
    def quota(self, project_id, user_id=None, key=None, value=None):
        """Create, update or display quotas for project/user

        If no quota key is provided, the quota will be displayed.
        If a valid quota key is provided and it does not exist,
        it will be created. Otherwise, it will be updated.
        """

        ctxt = context.get_admin_context()
        if user_id:
            quota = QUOTAS.get_user_quotas(ctxt, project_id, user_id)
        else:
            user_id = None
            quota = QUOTAS.get_project_quotas(ctxt, project_id)
        # if key is None, that means we need to show the quotas instead
        # of updating them
        if key:
            settable_quotas = QUOTAS.get_settable_quotas(ctxt,
                                                         project_id,
                                                         user_id=user_id)
            if key in quota:
                minimum = settable_quotas[key]['minimum']
                maximum = settable_quotas[key]['maximum']
                if value.lower() == 'unlimited':
                    value = -1
                if int(value) < -1:
                    print(_('Quota limit must be -1 or greater.'))
                    return (2)
                if ((int(value) < minimum) and
                    (maximum != -1 or (maximum == -1 and int(value) != -1))):
                    print(_('Quota limit must be greater than %s.') % minimum)
                    return (2)
                if maximum != -1 and int(value) > maximum:
                    print(_('Quota limit must be less than %s.') % maximum)
                    return (2)
                try:
                    db.quota_create(ctxt,
                                    project_id,
                                    key,
                                    value,
                                    user_id=user_id)
                except exception.QuotaExists:
                    db.quota_update(ctxt,
                                    project_id,
                                    key,
                                    value,
                                    user_id=user_id)
            else:
                print(
                    _('%(key)s is not a valid quota key. Valid options are: '
                      '%(options)s.') % {
                          'key': key,
                          'options': ', '.join(quota)
                      })
                return (2)
        print_format = "%-36s %-10s %-10s %-10s"
        print(print_format %
              (_('Quota'), _('Limit'), _('In Use'), _('Reserved')))
        # Retrieve the quota after update
        if user_id:
            quota = QUOTAS.get_user_quotas(ctxt, project_id, user_id)
        else:
            quota = QUOTAS.get_project_quotas(ctxt, project_id)
        for key, value in quota.iteritems():
            if value['limit'] < 0 or value['limit'] is None:
                value['limit'] = 'unlimited'
            print(print_format %
                  (key, value['limit'], value['in_use'], value['reserved']))
コード例 #29
0
    def update(self, req, id, body):
        context = req.environ['nova.context']
        authorize_update(context)
        project_id = id

        bad_keys = []

        # By default, we can force update the quota if the extended
        # is not loaded
        force_update = True
        extended_loaded = False
        if self.ext_mgr.is_loaded('os-extended-quotas'):
            # force optional has been enabled, the default value of
            # force_update need to be changed to False
            extended_loaded = True
            force_update = False

        user_id = None
        if self.ext_mgr.is_loaded('os-user-quotas'):
            # Update user quotas only if the extended is loaded
            params = urlparse.parse_qs(req.environ.get('QUERY_STRING', ''))
            user_id = params.get('user_id', [None])[0]

        try:
            settable_quotas = QUOTAS.get_settable_quotas(context,
                                                         project_id,
                                                         user_id=user_id)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()

        if not self.is_valid_body(body, 'quota_set'):
            msg = _("quota_set not specified")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        quota_set = body['quota_set']
        for key, value in quota_set.items():
            if (key not in QUOTAS and key not in NON_QUOTA_KEYS):
                bad_keys.append(key)
                continue
            if key == 'force' and extended_loaded:
                # only check the force optional when the extended has
                # been loaded
                force_update = strutils.bool_from_string(value)
            elif key not in NON_QUOTA_KEYS and value:
                try:
                    value = utils.validate_integer(value, key)
                except exception.InvalidInput as e:
                    raise webob.exc.HTTPBadRequest(
                        explanation=e.format_message())

        LOG.debug("force update quotas: %s", force_update)

        if len(bad_keys) > 0:
            msg = _("Bad key(s) %s in quota_set") % ",".join(bad_keys)
            raise webob.exc.HTTPBadRequest(explanation=msg)

        try:
            quotas = self._get_quotas(context,
                                      id,
                                      user_id=user_id,
                                      usages=True)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()

        for key, value in quota_set.items():
            if key in NON_QUOTA_KEYS or (not value and value != 0):
                continue
            # validate whether already used and reserved exceeds the new
            # quota, this check will be ignored if admin want to force
            # update
            value = int(value)
            if force_update is not True and value >= 0:
                quota_value = quotas.get(key)
                if quota_value and quota_value['limit'] >= 0:
                    quota_used = (quota_value['in_use'] +
                                  quota_value['reserved'])
                    LOG.debug(
                        "Quota %(key)s used: %(quota_used)s, "
                        "value: %(value)s.", {
                            'key': key,
                            'quota_used': quota_used,
                            'value': value
                        })
                    if quota_used > value:
                        msg = (_("Quota value %(value)s for %(key)s are "
                                 "less than already used and reserved "
                                 "%(quota_used)s") % {
                                     'value': value,
                                     'key': key,
                                     'quota_used': quota_used
                                 })
                        raise webob.exc.HTTPBadRequest(explanation=msg)

            minimum = settable_quotas[key]['minimum']
            maximum = settable_quotas[key]['maximum']
            self._validate_quota_limit(value, minimum, maximum)
            try:
                db.quota_create(context,
                                project_id,
                                key,
                                value,
                                user_id=user_id)
            except exception.QuotaExists:
                db.quota_update(context,
                                project_id,
                                key,
                                value,
                                user_id=user_id)
            except exception.AdminRequired:
                raise webob.exc.HTTPForbidden()
        return {'quota_set': self._get_quotas(context, id, user_id=user_id)}
コード例 #30
0
ファイル: quotas.py プロジェクト: Acidburn0zzz/nova
    def update(self, req, id, body):
        context = req.environ['nova.context']
        authorize_update(context)
        project_id = id

        bad_keys = []

        # By default, we can force update the quota if the extended
        # is not loaded
        force_update = True
        extended_loaded = False
        if self.ext_mgr.is_loaded('os-extended-quotas'):
            # force optional has been enabled, the default value of
            # force_update need to be changed to False
            extended_loaded = True
            force_update = False

        user_id = None
        if self.ext_mgr.is_loaded('os-user-quotas'):
            # Update user quotas only if the extended is loaded
            params = urlparse.parse_qs(req.environ.get('QUERY_STRING', ''))
            user_id = params.get('user_id', [None])[0]

        try:
            settable_quotas = QUOTAS.get_settable_quotas(context, project_id,
                                                         user_id=user_id)
        except exception.NotAuthorized:
            raise webob.exc.HTTPForbidden()

        for key, value in body['quota_set'].items():
            if (key not in QUOTAS and
                    key not in NON_QUOTA_KEYS):
                bad_keys.append(key)
                continue
            if key == 'force' and extended_loaded:
                # only check the force optional when the extended has
                # been loaded
                force_update = strutils.bool_from_string(value)
            elif key not in NON_QUOTA_KEYS and value:
                try:
                    value = int(value)
                except (ValueError, TypeError):
                    msg = _("Quota '%(value)s' for %(key)s should be "
                            "integer.") % {'value': value, 'key': key}
                    LOG.warn(msg)
                    raise webob.exc.HTTPBadRequest(explanation=msg)

        LOG.debug(_("force update quotas: %s") % force_update)

        if len(bad_keys) > 0:
            msg = _("Bad key(s) %s in quota_set") % ",".join(bad_keys)
            raise webob.exc.HTTPBadRequest(explanation=msg)

        try:
            quotas = self._get_quotas(context, id, user_id=user_id,
                                      usages=True)
        except exception.NotAuthorized:
            raise webob.exc.HTTPForbidden()

        for key, value in body['quota_set'].items():
            if key in NON_QUOTA_KEYS or (not value and value != 0):
                continue
            # validate whether already used and reserved exceeds the new
            # quota, this check will be ignored if admin want to force
            # update
            value = int(value)
            if force_update is not True and value >= 0:
                quota_value = quotas.get(key)
                if quota_value and quota_value['limit'] >= 0:
                    quota_used = (quota_value['in_use'] +
                                  quota_value['reserved'])
                    LOG.debug(_("Quota %(key)s used: %(quota_used)s, "
                                "value: %(value)s."),
                              {'key': key, 'quota_used': quota_used,
                               'value': value})
                    if quota_used > value:
                        msg = (_("Quota value %(value)s for %(key)s are "
                                "greater than already used and reserved "
                                "%(quota_used)s") %
                                {'value': value, 'key': key,
                                 'quota_used': quota_used})
                        raise webob.exc.HTTPBadRequest(explanation=msg)

            minimum = settable_quotas[key]['minimum']
            maximum = settable_quotas[key]['maximum']
            self._validate_quota_limit(value, minimum, maximum)
            try:
                db.quota_create(context, project_id, key, value,
                                user_id=user_id)
            except exception.QuotaExists:
                db.quota_update(context, project_id, key, value,
                                user_id=user_id)
            except exception.AdminRequired:
                raise webob.exc.HTTPForbidden()
        return {'quota_set': self._get_quotas(context, id, user_id=user_id)}
コード例 #31
0
ファイル: quota_sets.py プロジェクト: PFZheng/nova
    def update(self, req, id, body):
        context = req.environ['nova.context']
        authorize_update(context)
        project_id = id
        params = urlparse.parse_qs(req.environ.get('QUERY_STRING', ''))
        user_id = params.get('user_id', [None])[0]

        quota_set = body['quota_set']
        force_update = strutils.bool_from_string(quota_set.get('force',
                                                               'False'))

        try:
            settable_quotas = QUOTAS.get_settable_quotas(context, project_id,
                                                         user_id=user_id)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()

        try:
            quotas = self._get_quotas(context, id, user_id=user_id,
                                      usages=True)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()

        LOG.debug("Force update quotas: %s", force_update)

        for key, value in body['quota_set'].iteritems():
            if key == 'force' or (not value and value != 0):
                continue
            # validate whether already used and reserved exceeds the new
            # quota, this check will be ignored if admin want to force
            # update
            value = int(value)
            if force_update is not True and value >= 0:
                quota_value = quotas.get(key)
                if quota_value and quota_value['limit'] >= 0:
                    quota_used = (quota_value['in_use'] +
                                  quota_value['reserved'])
                    LOG.debug("Quota %(key)s used: %(quota_used)s, "
                              "value: %(value)s.",
                              {'key': key, 'quota_used': quota_used,
                               'value': value})
                    if quota_used > value:
                        msg = (_("Quota value %(value)s for %(key)s are "
                                "less than already used and reserved "
                                "%(quota_used)s") %
                                {'value': value, 'key': key,
                                 'quota_used': quota_used})
                        raise webob.exc.HTTPBadRequest(explanation=msg)

            minimum = settable_quotas[key]['minimum']
            maximum = settable_quotas[key]['maximum']
            self._validate_quota_limit(value, minimum, maximum)
            try:
                db.quota_create(context, project_id, key, value,
                                user_id=user_id)
            except exception.QuotaExists:
                db.quota_update(context, project_id, key, value,
                                user_id=user_id)
            except exception.AdminRequired:
                raise webob.exc.HTTPForbidden()
        return self._format_quota_set(id, self._get_quotas(context, id,
                                                           user_id=user_id))