Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
tvault_configurator / api / v1 / allowed_quotas.py
Size: Mime:
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright (c) 2020 TrilioData, Inc.
# All Rights Reserved.

"""The quota api."""
import webob
from webob import exc
from workloadmgr.api import wsgi
from workloadmgr import exception
from workloadmgr.common.constants import (
    quota_name_os_key_map, os_key_quota_name_map, quota_type_id_map
)
from workloadmgr.openstack.common import log as logging
from workloadmgr.workloads import workload_utils
from workloadmgr import workloads as workloadAPI
from ..validation_models import AllowedQuota

LOG = logging.getLogger(__name__)


class AllowedQuotasController(wsgi.Controller):
    """The allowed_quota API controller for the OpenStack API."""

    def __init__(self, ext_mgr=None):
        self.workload_api = workloadAPI.API()
        self.ext_mgr = ext_mgr
        super(AllowedQuotasController, self).__init__()

    def show(self, req, id):
        """Return data about the given allowed_quota."""
        try:
            try:
                context = req.environ["workloadmgr.context"]
                allowed_quota = self.workload_api.get_allowed_quotas(
                    context, allowed_quota_id=id) or []
            except exception.NotFound:
                raise exc.HTTPNotFound()
            if len(allowed_quota):
                return {
                    "allowed_quotas": AllowedQuota.deserialize(allowed_quota[0])
                }
            return {"allowed_quotas": {}}
        except exc.HTTPNotFound as error:
            raise error
        except exc.HTTPBadRequest as error:
            raise error
        except exc.HTTPServerError as error:
            raise error
        except Exception as error:
            raise exc.HTTPServerError(explanation=str(error))

    def index(self, req, id):
        """Returns a summary list of allowed_quotas."""
        try:
            context = req.environ["workloadmgr.context"]
            allowed_quotas = self.workload_api.get_allowed_quotas(
                context, project_id=id
            ) or []
            return {
                "allowed_quotas": [
                    AllowedQuota.deserialize(obj) for obj in allowed_quotas
                ]
            }
        except exc.HTTPNotFound as error:
            raise error
        except exc.HTTPBadRequest as error:
            raise error
        except exc.HTTPServerError as error:
            raise error
        except Exception as error:
            raise exc.HTTPServerError(explanation=str(error))

    def create(self, req, p_id, body):
        """Create new allowed quotas."""
        try:
            context = req.environ["workloadmgr.context"]
            existing_quota_types = {}
            try:
                allowed_quotas = self.workload_api.get_allowed_quotas(
                    context, p_id) or []
                if allowed_quotas:
                    existing_quota_types = {
                        allowed_quota.quota_type_id: allowed_quota.id
                        for allowed_quota in allowed_quotas
                    }
            except exception.AllowedQuotaNotFound as error:
                raise exc.HTTPNotFound(explanation=str(error))

            existing_quota_objs = {}
            try:
                new_quota_ids = [
                    data["quota_type_id"] for data in body['allowed_quotas']
                ]
                new_quota_objs = [
                    AllowedQuota(**data) for data in body['allowed_quotas']
                    if data["quota_type_id"] not in existing_quota_types
                ]

                for data in body['allowed_quotas']:
                    if data["quota_type_id"] in existing_quota_types \
                            and data["quota_type_id"] in new_quota_ids:
                        existing_quota_objs[
                            existing_quota_types[data["quota_type_id"]]
                        ] = AllowedQuota(**data)

            except ValueError as e:
                msg = _("Incorrect request body format, Error: {}".format(e))
                raise exc.HTTPBadRequest(explanation=msg)

            res = []
            try:
                if existing_quota_objs:
                    LOG.warn(
                        "Allowed Quota record is already present, "
                        "updating the existing records for ids: {}".format(
                            existing_quota_types)
                    )
                    for id, obj in existing_quota_objs.items():
                        updated_obj = self.workload_api.modify_allowed_quotas(
                            context, id, obj.to_dict()
                        )
                        res.append(AllowedQuota.deserialize(updated_obj))

                if new_quota_objs:
                    created_objs = self.workload_api.create_allowed_quotas(
                        context,
                        new_quota_objs
                    )
                    res.extend(
                        [AllowedQuota.deserialize(obj) for obj in created_objs]
                    )
                return {"allowed_quotas": res}
            except Exception as error:
                raise exc.HTTPServerError(explanation=str(error))
        except exc.HTTPNotFound as error:
            LOG.exception(error)
            raise error
        except exc.HTTPBadRequest as error:
            LOG.exception(error)
            raise error
        except exc.HTTPServerError as error:
            LOG.exception(error)
            raise error
        except Exception as error:
            LOG.exception(error)
            raise exc.HTTPServerError(explanation=str(error))

    @wsgi.response(202)
    def update(self, req, allowed_quota_id, body):
        """Update allowed quota."""
        try:
            context = req.environ["workloadmgr.context"]
            allowed_quota = []
            try:
                allowed_quota = self.workload_api.get_allowed_quotas(
                    context, allowed_quota_id=allowed_quota_id) or []
            except exception.AllowedQuotaNotFound as error:
                raise exc.HTTPNotFound(explanation=str(error))
            obj = None
            try:
                data = body.get("allowed_quotas", {})
                if len(allowed_quota):
                    existing_quota = AllowedQuota.deserialize(allowed_quota[0])
                    if not data.get("project_id"):
                        data["project_id"] = context.project_id
                    existing_quota.update(data)
                    existing_quota.pop("id", None)
                    existing_quota.pop("version", None)
                    existing_quota.pop("quota_type_name", None)
                    obj = AllowedQuota(**existing_quota)
            except ValueError as e:
                msg = _("Incorrect request body format, Error: {}".format(e))
                raise exc.HTTPBadRequest(explanation=msg)

            try:
                updated_obj = self.workload_api.modify_allowed_quotas(
                    context, allowed_quota_id, obj.to_dict()
                )
                return {"allowed_quotas": [
                    AllowedQuota.deserialize(updated_obj)
                ]}
            except exception.AllowedQuotaNotFound as error:
                raise exc.HTTPNotFound(explanation=str(error))
        except exc.HTTPNotFound as error:
            LOG.exception(error)
            raise error
        except exc.HTTPBadRequest as error:
            LOG.exception(error)
            raise error
        except exc.HTTPServerError as error:
            LOG.exception(error)
            raise error
        except Exception as error:
            LOG.exception(error)
            raise exc.HTTPServerError(explanation=str(error))

    @wsgi.response(202)
    def upsert_all(self, req, p_id, body):
        """Update allowed quota."""
        try:
            context = req.environ["workloadmgr.context"]
            allowed_quota = []
            try:
                allowed_quota = self.workload_api.get_allowed_quotas(
                    context, p_id) or []
            except exception.AllowedQuotaNotFound as error:
                raise exc.HTTPNotFound(explanation=str(error))

            try:
                data = body.get("quotas", {})
                if len(allowed_quota):
                    for quota in allowed_quota:
                        existing_quota = AllowedQuota.deserialize(quota)
                        data_key = quota_name_os_key_map.get(
                            existing_quota["quota_type_name"], None
                        )
                        if data_key and data_key in data:
                            if existing_quota["allowed_value"] != data[data_key]:
                                existing_quota["allowed_value"] = data[data_key]
                                q_id = existing_quota["id"]
                                existing_quota.pop("id", None)
                                existing_quota.pop("version", None)
                                existing_quota.pop("quota_type_name", None)
                                existing_quota.pop("high_watermark", None)
                                obj = AllowedQuota(**existing_quota)
                                self.workload_api.modify_allowed_quotas(
                                    context, q_id, obj.to_dict()
                                )
                            data.pop(data_key, None)

                if data:
                    new_quota_objs = []
                    for key, value in data.items():
                        quota_type_name = os_key_quota_name_map.get(key, None)
                        if quota_type_name:
                            obj = AllowedQuota(**{
                                "project_id": p_id,
                                "quota_type_id":
                                    quota_type_id_map[quota_type_name],
                                "allowed_value": value
                            })
                            new_quota_objs.append(obj)
                    if new_quota_objs:
                        self.workload_api.create_allowed_quotas(
                            context,
                            new_quota_objs
                        )
            except exception.AllowedQuotaNotFound as error:
                raise exc.HTTPNotFound(explanation=str(error))
        except exc.HTTPNotFound as error:
            LOG.exception(error)
            raise error
        except exc.HTTPBadRequest as error:
            LOG.exception(error)
            raise error
        except exc.HTTPServerError as error:
            LOG.exception(error)
            raise error
        except Exception as error:
            LOG.exception(error)
            raise exc.HTTPServerError(explanation=str(error))

    def delete(self, req, allowed_quota_id):
        """Delete a workload."""
        try:
            context = req.environ["workloadmgr.context"]
            self.workload_api.delete_allowed_quota(context, allowed_quota_id)
            return webob.Response(status_int=202)
        except exception.AllowedQuotaNotFound as error:
            LOG.exception(error)
            raise exc.HTTPNotFound(explanation=str(error))
        except exception.InvalidState as error:
            LOG.exception(error)
            raise exc.HTTPBadRequest(explanation=str(error))
        except Exception as error:
            LOG.exception(error)
            raise exc.HTTPServerError(explanation=str(error))


def create_resource(ext_mgr):
    return wsgi.Resource(AllowedQuotasController(ext_mgr))