Ejemplo n.º 1
0
    def _delete_project_quota(self, req, id,body):
        context = req.environ['nova.context']
        # id is made equivalent to project_id for better readability
        project_id = id
        child_list = []
        parent_id = None
        if hasattr(context, 'auth_token') and hasattr(context, 'project_id'):
            if(context.auth_token and context.project_id):
                token = context.auth_token
                headers = {"X-Auth-Token": token,
                           "Content-type": "application/json",
                           "Accept": "text/json"}
                """params = {}
                auth_host = KEYSTONE_CONF.keystone_authtoken.auth_host
                auth_port = int(KEYSTONE_CONF.keystone_authtoken.auth_port)
                auth_server = '%s:%s' % (auth_host,auth_port)

                The follwing url is used for checking whether the given
                project is a root project or not

                auth_url = '/%s/%s/%s' % ("v3","projects",project_id)
                conn = httplib.HTTPConnection(auth_server)
                conn.request("GET", auth_url, json.dumps(params), headers=headers)
                response = conn.getresponse()
                data = response.read()
                data = json.loads(data)

                if not "project" in data:
                     raise webob.exc.HTTPForbidden()
                try:
                    parent_id = data["project"]["parent_id"]
                except:
                    pass"""
       
                parent_id = self._get_parent_id ( headers , project_id )
                target = {"project_id":parent_id}
                try:
                    if parent_id:
                        authorize_update(context,target = target)
                        nova.context.authorize_root_or_parent_project_context(context,parent_id)
                    else:
                        authorize_root_update(context)
                        nova.context.authorize_root_or_parent_project_context(context,project_id)
                except exception.Forbidden:
                    raise webob.exc.HTTPForbidden()
                
                if parent_id :
                    child_list = self._get_immediate_child_list( headers , parent_id )
                else:
                    child_list = self._get_immediate_child_list( headers , project_id )
                # The following url is for finding the subtree

                """if parent_id:
                    auth_url = '/%s/%s/%s?%s' % ("v3","projects",parent_id,"subtree")
                else:
                    auth_url = '/%s/%s/%s?%s' % ("v3","projects",project_id,"subtree")
                
                conn.request("GET", auth_url, json.dumps(params), headers=headers)
                response = conn.getresponse()
                data = response.read()
                data = json.loads(data)
                subtree=[]
                try:
                    subtree = data["project"]["subtree"]
                except:
                    pass
                for item in subtree:
                    project_info = item["project"]
                    try:
                        if project_info["parent_id"] == parent_id:
                           child_list.append(project_info["id"])
                    except:
                        pass"""
        if parent_id is not None:
            if id not in child_list:
                raise exception.InvalidParent(parent_id=parent_id,project_id=project_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,
                                                         parent_id,user_id=user_id)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()

        LOG.debug("Force update quotas: %s", force_update)
        p = body['quota_set']
        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 not force_update:
                minimum = settable_quotas[key]['minimum']
                maximum = settable_quotas[key]['maximum']
                self._validate_quota_limit(key, value, minimum, maximum)
            try:
                objects.Quotas.create_limit(context, project_id,
                                            key, value, user_id=user_id)
            except exception.QuotaExists:
                objects.Quotas.update_limit(context, project_id,
                                            key, value, user_id=user_id)
            except exception.AdminRequired:
                raise webob.exc.HTTPForbidden()

            if parent_id:
                db.quota_allocated_update(context, parent_id,child_list)
Ejemplo n.º 2
0
    def update(self, req, id, body):
        context = req.environ['nova.context']
        # id is made equivalent to project_id for better readability
        project_id = id
        child_list = []
        parent_id = None
        params = urlparse.parse_qs(req.environ.get('QUERY_STRING', ''))
        user_id = params.get('user_id', [None])[0]
        if hasattr(context, 'auth_token') and hasattr(context, 'project_id'):
            if (context.auth_token and context.project_id):
                token = context.auth_token
                headers = {
                    "X-Auth-Token": token,
                    "Content-type": "application/json",
                    "Accept": "text/json"
                }
                parent_id = self._get_parent_id(headers, project_id)
                target = {"project_id": parent_id}
                try:
                    if user_id:
                        authorize_update(context)
                        nova.context.authorize_project_context(context, id)
                    else:
                        if parent_id:
                            authorize_update(context, target=target)
                            nova.context.authorize_root_or_parent_project_context(
                                context, parent_id)
                        else:
                            authorize_root_update(context)
                            nova.context.authorize_root_or_parent_project_context(
                                context, project_id)
                except exception.Forbidden:
                    raise webob.exc.HTTPForbidden()

                if parent_id:
                    child_list = self._get_immediate_child_list(
                        headers, parent_id)
                else:
                    child_list = self._get_immediate_child_list(
                        headers, project_id)

        if parent_id is not None:
            if id not in child_list:
                raise exception.InvalidParent(parent_id=parent_id,
                                              project_id=project_id)

        ################
        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,
                                                         parent_id,
                                                         user_id=user_id)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()
        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 not force_update:
                minimum = settable_quotas[key]['minimum']
                maximum = settable_quotas[key]['maximum']
                self._validate_quota_limit(key, value, minimum, maximum)
            try:
                objects.Quotas.create_limit(context,
                                            project_id,
                                            key,
                                            value,
                                            user_id=user_id)
            except exception.QuotaExists:
                objects.Quotas.update_limit(context,
                                            project_id,
                                            key,
                                            value,
                                            user_id=user_id)
            if parent_id:
                db.quota_allocated_update(context, parent_id, child_list)
        return self._format_quota_set(
            id, self._get_quotas(context, id, user_id=user_id))
Ejemplo n.º 3
0
    def update(self, req, id, body):
        context = req.environ['nova.context']
        authorize_update(context)
        project_id = id
        child_list = []
        parent_id = None
        if hasattr(context, 'auth_token') and hasattr(context, 'project_id'):
            if (context.auth_token and context.project_id):
                token = context.auth_token
                headers = {
                    "X-Auth-Token": token,
                    "Content-type": "application/json",
                    "Accept": "text/json"
                }
                params = {}
                auth_host = KEYSTONE_CONF.keystone_authtoken.auth_host
                auth_port = int(KEYSTONE_CONF.keystone_authtoken.auth_port)
                auth_server = '%s:%s' % (auth_host, auth_port)
                """ The keytsone output for the following url is used for
                checking whether the given project is a root project or not """

                auth_url = '/%s/%s/%s' % ("v3", "projects", project_id)
                conn = httplib.HTTPConnection(auth_server)
                conn.request("GET",
                             auth_url,
                             json.dumps(params),
                             headers=headers)
                response = conn.getresponse()
                data = response.read()
                data = json.loads(data)
                if not "project" in data:
                    raise webob.exc.HTTPForbidden()

                try:
                    parent_id = data["project"]["parent_id"]
                except:
                    pass

                target = {"project_id": parent_id}
                try:
                    if parent_id:
                        authorize_update(context, target=target)
                        nova.context.authorize_root_or_parent_project_context(
                            context, parent_id)
                    else:
                        authorize_root_update(context)
                        nova.context.authorize_root_or_parent_project_context(
                            context, project_id)
                except exception.Forbidden:
                    raise webob.exc.HTTPForbidden()

                # The following url is for finding the subtree

                if parent_id:
                    auth_url = '/%s/%s/%s?%s' % ("v3", "projects", parent_id,
                                                 "subtree")
                else:
                    auth_url = '/%s/%s/%s?%s' % ("v3", "projects", project_id,
                                                 "subtree")

                conn.request("GET",
                             auth_url,
                             json.dumps(params),
                             headers=headers)
                response = conn.getresponse()
                data = response.read()
                data = json.loads(data)
                subtree = []
                try:
                    subtree = data["project"]["subtree"]
                except:
                    pass
                for item in subtree:
                    project_info = item["project"]
                    try:
                        if project_info["parent_id"] == parent_id:
                            child_list.append(project_info["id"])
                    except:
                        pass
        if parent_id is not None:
            if id not in child_list:
                raise exception.InvalidParent(parent_id=parent_id,
                                              project_id=project_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,
                                                         parent_id,
                                                         user_id=user_id)
        except exception.Forbidden:
            raise webob.exc.HTTPForbidden()

        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]

        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 self.supported_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)

        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 not force_update:
                minimum = settable_quotas[key]['minimum']
                maximum = settable_quotas[key]['maximum']
                self._validate_quota_limit(key, value, minimum, maximum)
            try:
                objects.Quotas.create_limit(context,
                                            project_id,
                                            key,
                                            value,
                                            user_id=user_id)
            except exception.QuotaExists:
                objects.Quotas.update_limit(context,
                                            project_id,
                                            key,
                                            value,
                                            user_id=user_id)
            if parent_id:
                db.quota_allocated_update(context, parent_id, child_list)
            else:
                db.quota_allocated_update(context, project_id, child_list)
        return self._format_quota_set(
            id, self._get_quotas(context, id, user_id=user_id))