diff options
Diffstat (limited to 'genericparser/packages/views')
-rw-r--r-- | genericparser/packages/views/__init__.py | 13 | ||||
-rw-r--r-- | genericparser/packages/views/catalog_views.py | 535 | ||||
-rw-r--r-- | genericparser/packages/views/common.py | 95 | ||||
-rw-r--r-- | genericparser/packages/views/health_check_views.py | 31 | ||||
-rw-r--r-- | genericparser/packages/views/ns_descriptor_views.py | 139 | ||||
-rw-r--r-- | genericparser/packages/views/nsdm_subscription_views.py | 259 | ||||
-rw-r--r-- | genericparser/packages/views/pnf_descriptor_views.py | 173 | ||||
-rw-r--r-- | genericparser/packages/views/vnf_package_artifact_views.py | 54 | ||||
-rw-r--r-- | genericparser/packages/views/vnf_package_subscription_views.py | 161 | ||||
-rw-r--r-- | genericparser/packages/views/vnf_package_views.py | 169 |
10 files changed, 1629 insertions, 0 deletions
diff --git a/genericparser/packages/views/__init__.py b/genericparser/packages/views/__init__.py new file mode 100644 index 0000000..342c2a8 --- /dev/null +++ b/genericparser/packages/views/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2018 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/genericparser/packages/views/catalog_views.py b/genericparser/packages/views/catalog_views.py new file mode 100644 index 0000000..ed10e68 --- /dev/null +++ b/genericparser/packages/views/catalog_views.py @@ -0,0 +1,535 @@ +# Copyright 2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import uuid + +from drf_yasg import openapi +from drf_yasg.utils import no_body, swagger_auto_schema +from rest_framework import status +from rest_framework.decorators import api_view +from rest_framework.response import Response +from genericparser.packages.biz import sdc_vnf_package, sdc_ns_package +from genericparser.packages.biz.pnf_descriptor import PnfDescriptor +from genericparser.packages.biz.sdc_service_package import ServicePackage +from genericparser.packages.serializers.genericparser_serializers import InternalErrorRequestSerializer, \ + ServicePackageDistributeRequestSerializer, ServicePackagesSerializer, ServicePackageSerializer +from genericparser.packages.serializers.genericparser_serializers import NfPackageDistributeRequestSerializer +from genericparser.packages.serializers.genericparser_serializers import NfPackageSerializer +from genericparser.packages.serializers.genericparser_serializers import NfPackagesSerializer +from genericparser.packages.serializers.genericparser_serializers import NsPackageDistributeRequestSerializer +from genericparser.packages.serializers.genericparser_serializers import NsPackageDistributeResponseSerializer +from genericparser.packages.serializers.genericparser_serializers import NsPackageSerializer +from genericparser.packages.serializers.genericparser_serializers import NsPackagesSerializer +from genericparser.packages.serializers.genericparser_serializers import ParseModelRequestSerializer +from genericparser.packages.serializers.genericparser_serializers import ParseModelResponseSerializer +from genericparser.packages.serializers.genericparser_serializers import PostJobResponseSerializer +from genericparser.packages.views.common import fmt_error_rsp +from genericparser.pub.exceptions import PackageNotFoundException, PackageHasExistsException +from genericparser.pub.utils.syscomm import fun_name +from genericparser.pub.utils.values import ignore_case_get + +logger = logging.getLogger(__name__) + + +@swagger_auto_schema( + method='POST', + operation_description="On distribute NS package", + request_body=NsPackageDistributeRequestSerializer, + responses={ + status.HTTP_202_ACCEPTED: NsPackageDistributeResponseSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: InternalErrorRequestSerializer}) +@swagger_auto_schema( + method='GET', + operation_description="Query NS packages", + request_body=no_body, + responses={ + status.HTTP_200_OK: NsPackagesSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: InternalErrorRequestSerializer}) +@api_view(http_method_names=['POST', 'GET']) +def nspackages_rc(request, *args, **kwargs): + logger.debug("Enter %s, method is %s", fun_name(), request.method) + ret, normal_status, response_serializer, validation_error = None, None, None, None + + if request.method == 'GET': + # Gets ns package list + ret = sdc_ns_package.ns_get_csars() + normal_status = status.HTTP_200_OK + + if ret[0] == 0: + response_serializer = NsPackagesSerializer(data=ret[1]) + validation_error = handleValidatonError( + response_serializer, False) + if validation_error: + return validation_error + elif request.method == 'POST': + # Distributes the package accroding to the given csarId + request_serializer = NsPackageDistributeRequestSerializer(data=request.data) + validation_error = handleValidatonError(request_serializer, True) + if validation_error: + return validation_error + + csar_id = ignore_case_get(request.data, "csarId") + logger.debug("csar_id is %s", csar_id) + ret = sdc_ns_package.ns_on_distribute(csar_id) + normal_status = status.HTTP_202_ACCEPTED + + logger.debug("Leave %s, Return value is %s", fun_name(), ret) + if ret[0] != 0: + return Response( + data={ + 'error': ret[1]}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + return Response(data=ret[1], status=normal_status) + + +@swagger_auto_schema( + method='POST', + operation_description="On distribute Nf package", + request_body=NfPackageDistributeRequestSerializer(), + responses={ + status.HTTP_202_ACCEPTED: PostJobResponseSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: InternalErrorRequestSerializer}) +@swagger_auto_schema( + method='GET', + operation_description="Query Nf packages", + request_body=no_body, + responses={ + status.HTTP_200_OK: NfPackagesSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: InternalErrorRequestSerializer}) +@api_view(http_method_names=['POST', 'GET']) +def nfpackages_rc(request, *args, **kwargs): + logger.debug( + "Enter %s%s, method is %s", + fun_name(), + request.data, + request.method) + ret, normal_status, response_serializer, validation_error = None, None, None, None + if request.method == 'GET': + ret = sdc_vnf_package.nf_get_csars() + normal_status = status.HTTP_200_OK + response_serializer = NfPackagesSerializer(data=ret[1]) + elif request.method == 'POST': + request_serivalizer = NfPackageDistributeRequestSerializer( + data=request.data) + validation_error = handleValidatonError( + request_serivalizer, True) + if validation_error: + return validation_error + + csar_id = ignore_case_get(request_serivalizer.data, "csarId") + vim_ids = ignore_case_get(request_serivalizer.data, "vimIds") + lab_vim_id = ignore_case_get(request_serivalizer.data, "labVimId") + job_id = str(uuid.uuid4()) + sdc_vnf_package.NfDistributeThread( + csar_id, vim_ids, lab_vim_id, job_id).start() + ret = [0, {"jobId": job_id}] + normal_status = status.HTTP_202_ACCEPTED + + response_serializer = PostJobResponseSerializer(data=ret[1]) + logger.debug("Leave %s, Return value is %s", fun_name(), ret) + + if ret[0] != 0: + return Response( + data={ + 'error': ret[1]}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + validation_error = handleValidatonError( + response_serializer, False) + if validation_error: + return validation_error + + return Response(data=response_serializer.data, status=normal_status) + + +@swagger_auto_schema( + method='DELETE', + operation_description="Delete one NS package", + request_body=no_body, + manual_parameters=[ + openapi.Parameter( + 'csarId', + openapi.IN_QUERY, + "csarId", + type=openapi.TYPE_STRING)], + responses={ + status.HTTP_200_OK: NsPackageDistributeResponseSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: openapi.Response( + 'error message', + openapi.Schema( + type=openapi.TYPE_STRING))}) +@swagger_auto_schema( + method='GET', + operation_description="Query one NS package", + request_body=no_body, + manual_parameters=[ + openapi.Parameter( + 'csarId', + openapi.IN_QUERY, + "csarId", + type=openapi.TYPE_STRING)], + responses={ + status.HTTP_200_OK: NsPackageSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: openapi.Response( + 'error message', + openapi.Schema( + type=openapi.TYPE_STRING))}) +@api_view(http_method_names=['DELETE', 'GET']) +def ns_rd_csar(request, *args, **kwargs): + csar_id = ignore_case_get(kwargs, "csarId") + logger.info("Enter %s, method is %s, csar_id is %s", + fun_name(), request.method, csar_id) + ret, normal_status, response_serializer, validation_error = None, None, None, None + if request.method == 'GET': + ret = sdc_ns_package.ns_get_csar(csar_id) + normal_status = status.HTTP_200_OK + if ret[0] == 0: + response_serializer = NsPackageSerializer(data=ret[1]) + validation_error = handleValidatonError(response_serializer, False) + if validation_error: + return validation_error + elif request.method == 'DELETE': + ret = sdc_ns_package.ns_delete_csar(csar_id) + normal_status = status.HTTP_200_OK + logger.info("Leave %s, Return value is %s", fun_name(), ret) + if ret[0] != 0: + return Response( + data={ + 'error': ret[1]}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) + return Response(data=ret[1], status=normal_status) + + +@swagger_auto_schema( + method='POST', + operation_description="On distribute Service package", + request_body=ServicePackageDistributeRequestSerializer, + responses={ + status.HTTP_202_ACCEPTED: "", + status.HTTP_400_BAD_REQUEST: InternalErrorRequestSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: InternalErrorRequestSerializer}) +@swagger_auto_schema( + method='GET', + operation_description="Query Service packages", + request_body=no_body, + responses={ + status.HTTP_200_OK: ServicePackagesSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: InternalErrorRequestSerializer}) +@api_view(http_method_names=['POST', 'GET']) +def servicepackages_rc(request, *args, **kwargs): + logger.debug("Enter %s, method is %s", fun_name(), request.method) + + if request.method == 'GET': + # Gets service package list + try: + csar_list = ServicePackage().get_csars() + response_serializer = ServicePackagesSerializer(data=csar_list) + validation_error = handleValidatonError(response_serializer, False) + if validation_error: + return validation_error + return Response(data=csar_list, status=status.HTTP_200_OK) + except Exception as e: + error_status = status.HTTP_500_INTERNAL_SERVER_ERROR + return Response(data=fmt_error_rsp(e.message, error_status), status=error_status) + elif request.method == 'POST': + # Distributes the package according to the given csarId + request_serializer = ServicePackageDistributeRequestSerializer(data=request.data) + validation_error = handleValidatonError(request_serializer, True) + if validation_error: + return validation_error + + csar_id = ignore_case_get(request.data, "csarId") + logger.debug("csar_id is %s", csar_id) + try: + ServicePackage().on_distribute(csar_id) + return Response(status=status.HTTP_202_ACCEPTED) + except PackageHasExistsException as e: + error_status = status.HTTP_400_BAD_REQUEST + return Response(data=fmt_error_rsp(e.message, error_status), status=error_status) + except Exception as e: + error_status = status.HTTP_500_INTERNAL_SERVER_ERROR + return Response(data=fmt_error_rsp(e.message, error_status), status=error_status) + + +@swagger_auto_schema( + method='DELETE', + operation_description="Delete one Service package", + request_body=no_body, + manual_parameters=[ + openapi.Parameter( + 'csarId', + openapi.IN_QUERY, + "csarId", + type=openapi.TYPE_STRING)], + responses={ + status.HTTP_204_NO_CONTENT: "", + status.HTTP_404_NOT_FOUND: InternalErrorRequestSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: InternalErrorRequestSerializer}) +@swagger_auto_schema( + method='GET', + operation_description="Query one Service package", + request_body=no_body, + manual_parameters=[ + openapi.Parameter( + 'csarId', + openapi.IN_QUERY, + "csarId", + type=openapi.TYPE_STRING)], + responses={ + status.HTTP_200_OK: ServicePackageSerializer, + status.HTTP_404_NOT_FOUND: InternalErrorRequestSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: InternalErrorRequestSerializer}) +@api_view(http_method_names=['DELETE', 'GET']) +def service_rd_csar(request, *args, **kwargs): + csar_id = ignore_case_get(kwargs, "csarId") + logger.info("Enter %s, method is %s, csar_id is %s", fun_name(), request.method, csar_id) + + if request.method == 'GET': + try: + ret = ServicePackage().get_csar(csar_id) + response_serializer = ServicePackageSerializer(data=ret) + validation_error = handleValidatonError(response_serializer, False) + if validation_error: + return validation_error + return Response(data=ret, status=status.HTTP_200_OK) + except PackageNotFoundException as e: + error_status = status.HTTP_404_NOT_FOUND + return Response(data=fmt_error_rsp(e.message, error_status), status=error_status) + except Exception as e: + error_status = status.HTTP_500_INTERNAL_SERVER_ERROR + return Response(data=fmt_error_rsp(e.message, error_status), status=error_status) + + elif request.method == 'DELETE': + try: + ServicePackage().delete_csar(csar_id) + return Response(status=status.HTTP_204_NO_CONTENT) + except PackageNotFoundException as e: + error_status = status.HTTP_404_NOT_FOUND + return Response(data=fmt_error_rsp(e.message, error_status), status=error_status) + except Exception as e: + error_status = status.HTTP_500_INTERNAL_SERVER_ERROR + return Response(data=fmt_error_rsp(e.message, error_status), status=error_status) + + +@swagger_auto_schema( + method='DELETE', + operation_description="Delete one Nf package", + request_body=no_body, + manual_parameters=[ + openapi.Parameter( + 'csarId', + openapi.IN_QUERY, + "csarId", + type=openapi.TYPE_STRING)], + responses={ + status.HTTP_202_ACCEPTED: PostJobResponseSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: openapi.Response( + 'error message', + openapi.Schema( + type=openapi.TYPE_STRING))}) +@swagger_auto_schema( + method='GET', + operation_description="Query one Nf package", + request_body=no_body, + manual_parameters=[ + openapi.Parameter( + 'csarId', + openapi.IN_QUERY, + "csarId", + type=openapi.TYPE_STRING)], + responses={ + status.HTTP_200_OK: NfPackageSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: openapi.Response( + 'error message', + openapi.Schema( + type=openapi.TYPE_STRING))}) +@api_view(http_method_names=['DELETE', 'GET']) +def nf_rd_csar(request, *args, **kwargs): + csar_id = ignore_case_get(kwargs, "csarId") + logger.info("Enter %s, method is %s, csar_id is %s", + fun_name(), request.method, csar_id) + ret, normal_status, response_serializer, validation_error = None, None, None, None + + if request.method == 'GET': + ret = sdc_vnf_package.nf_get_csar(csar_id) + normal_status = status.HTTP_200_OK + response_serializer = NfPackageSerializer(data=ret[1]) + + elif request.method == 'DELETE': + job_id = str(uuid.uuid4()) + sdc_vnf_package.NfPkgDeleteThread(csar_id, job_id).start() + ret = [0, {"jobId": job_id}] + normal_status = status.HTTP_202_ACCEPTED + response_serializer = PostJobResponseSerializer(data=ret[1]) + + logger.info("Leave %s, Return value is %s", fun_name(), ret) + if ret[0] != 0: + return Response( + data={ + 'error': ret[1]}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + validation_error = handleValidatonError( + response_serializer, False) + if validation_error: + return validation_error + + return Response(data=response_serializer.data, status=normal_status) + + +@swagger_auto_schema( + method='POST', + operation_description="Parse model(NS, Service, VNF, PNF)", + request_body=ParseModelRequestSerializer, + responses={ + status.HTTP_202_ACCEPTED: ParseModelResponseSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: InternalErrorRequestSerializer}) +@api_view(http_method_names=['POST']) +def model_parser(request, *args, **kwargs): + csar_id = ignore_case_get(request.data, "csarId") + package_type = ignore_case_get(request.data, "packageType") + inputs = ignore_case_get(request.data, "inputs") + logger.debug( + "Enter %s, csar_id=%s, package_type=%s, inputs=%s", + fun_name(), + csar_id, + package_type, + inputs) + + if package_type.lower().__eq__("service"): + try: + ret = ServicePackage().parse_serviced(csar_id, inputs) + response_serializer = ParseModelResponseSerializer(data=ret) + validation_error = handleValidatonError( + response_serializer, False) + if validation_error: + return validation_error + return Response(data=response_serializer.data, status=status.HTTP_202_ACCEPTED) + except PackageNotFoundException as e: + error_status = status.HTTP_404_NOT_FOUND + return Response(data=fmt_error_rsp(e.message, error_status), status=error_status) + except Exception as e: + error_status = status.HTTP_500_INTERNAL_SERVER_ERROR + return Response(data=fmt_error_rsp(e.message, error_status), status=error_status) + elif package_type.lower().__eq__("ns"): + ret = sdc_ns_package.parse_nsd(csar_id, inputs) + elif package_type.lower().__eq__("vnf"): + ret = sdc_vnf_package.parse_vnfd(csar_id, inputs) + elif package_type.lower().__eq__("pnf"): + ret = PnfDescriptor().parse_pnfd(csar_id, inputs) + else: + error_status = status.HTTP_400_BAD_REQUEST + error_message = "Invalid package type, it should be one of [VNF, PNF, NS, Service]" + return Response(data=fmt_error_rsp(error_message, error_status), status=error_status) + + if ret[0] != 0: + return Response( + data={ + 'error': ret[1]}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + response_serializer = ParseModelResponseSerializer(data=ret[1]) + validation_error = handleValidatonError( + response_serializer, False) + if validation_error: + return validation_error + + return Response(data=response_serializer.data, status=status.HTTP_202_ACCEPTED) + + +@swagger_auto_schema( + method='POST', + operation_description="Parse NS model", + request_body=ParseModelRequestSerializer, + responses={ + status.HTTP_202_ACCEPTED: ParseModelResponseSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: InternalErrorRequestSerializer}) +@api_view(http_method_names=['POST']) +def ns_model_parser(request, *args, **kwargs): + csar_id = ignore_case_get(request.data, "csarId") + inputs = ignore_case_get(request.data, "inputs") + logger.debug( + "Enter %s, csar_id=%s, inputs=%s", + fun_name(), + csar_id, + inputs) + ret = sdc_ns_package.parse_nsd(csar_id, inputs) + logger.info("Leave %s, Return value is %s", fun_name(), ret) + if ret[0] != 0: + return Response( + data={ + 'error': ret[1]}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + response_serializer = ParseModelResponseSerializer(data=ret[1]) + validation_error = handleValidatonError( + response_serializer, False) + if validation_error: + return validation_error + + return Response(data=response_serializer.data, status=status.HTTP_202_ACCEPTED) + + +@swagger_auto_schema( + method='POST', + operation_description="Parse NF model", + request_body=ParseModelRequestSerializer, + responses={ + status.HTTP_202_ACCEPTED: ParseModelResponseSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: InternalErrorRequestSerializer}) +@api_view(http_method_names=['POST']) +def vnf_model_parser(request, *args, **kwargs): + csar_id = ignore_case_get(request.data, "csarId") + inputs = ignore_case_get(request.data, "inputs") + logger.debug( + "Enter %s, csar_id=%s, inputs=%s", + fun_name(), + csar_id, + inputs) + ret = sdc_vnf_package.parse_vnfd(csar_id, inputs) + logger.info("Leave %s, Return value is %s", fun_name(), ret) + if ret[0] != 0: + return Response( + data={ + 'error': ret[1]}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + response_serializer = ParseModelResponseSerializer(data=ret[1]) + validation_error = handleValidatonError( + response_serializer, False) + if validation_error: + return validation_error + + return Response(data=response_serializer.data, status=status.HTTP_202_ACCEPTED) + + +def handleValidatonError(base_serializer, is_request): + response = None + + if not base_serializer.is_valid(): + errormessage = base_serializer.errors + logger.error(errormessage) + + if is_request: + message = 'Invalid request' + else: + message = 'Invalid response' + logger.error(message) + response = Response( + data={'error': errormessage}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + return response diff --git a/genericparser/packages/views/common.py b/genericparser/packages/views/common.py new file mode 100644 index 0000000..70637a9 --- /dev/null +++ b/genericparser/packages/views/common.py @@ -0,0 +1,95 @@ +# Copyright 2018 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import traceback +import logging + +from rest_framework import status +from rest_framework.response import Response + +from genericparser.pub.exceptions import GenericparserException +from genericparser.pub.exceptions import NsdmBadRequestException +from genericparser.pub.exceptions import PackageNotFoundException +from genericparser.pub.exceptions import ResourceNotFoundException +from genericparser.pub.exceptions import ArtifactNotFoundException + +logger = logging.getLogger(__name__) + + +def validate_data(data, serializer): + serialized_data = serializer(data=data) + if not serialized_data.is_valid(): + logger.error('Data validation failed.') + raise GenericparserException(serialized_data.errors) + return serialized_data + + +def fmt_error_rsp(error_message, status): + return {"errorMessage": error_message, "error": status} + + +def make_error_resp(status, detail): + return Response( + data={ + 'status': status, + 'detail': detail + }, + status=status + ) + + +def view_safe_call_with_log(logger): + def view_safe_call(func): + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except PackageNotFoundException as e: + logger.error(e.message) + return make_error_resp( + detail=e.message, + status=status.HTTP_404_NOT_FOUND + ) + except ResourceNotFoundException as e: + logger.error(e.message) + return make_error_resp( + detail=e.message, + status=status.HTTP_404_NOT_FOUND + ) + except ArtifactNotFoundException as e: + logger.error(e.message) + return make_error_resp( + detail=e.message, + status=status.HTTP_404_NOT_FOUND + ) + except NsdmBadRequestException as e: + logger.error(e.message) + return make_error_resp( + detail=e.message, + status=status.HTTP_400_BAD_REQUEST + ) + except GenericparserException as e: + logger.error(e.message) + return make_error_resp( + detail=e.message, + status=status.HTTP_500_INTERNAL_SERVER_ERROR + ) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + return make_error_resp( + detail='Unexpected exception', + status=status.HTTP_500_INTERNAL_SERVER_ERROR + ) + return wrapper + return view_safe_call diff --git a/genericparser/packages/views/health_check_views.py b/genericparser/packages/views/health_check_views.py new file mode 100644 index 0000000..cc1a379 --- /dev/null +++ b/genericparser/packages/views/health_check_views.py @@ -0,0 +1,31 @@ +# Copyright (c) 2019, CMCC Technologies Co., Ltd. + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +from drf_yasg.utils import swagger_auto_schema +from rest_framework import status +from rest_framework.response import Response +from rest_framework.views import APIView + +logger = logging.getLogger(__name__) + + +class HealthCheckView(APIView): + @swagger_auto_schema( + responses={ + status.HTTP_200_OK: 'Active'}) + def get(self, request, format=None): + logger.debug("Health check.") + return Response({"status": "active"}) diff --git a/genericparser/packages/views/ns_descriptor_views.py b/genericparser/packages/views/ns_descriptor_views.py new file mode 100644 index 0000000..86a3e9e --- /dev/null +++ b/genericparser/packages/views/ns_descriptor_views.py @@ -0,0 +1,139 @@ +# Copyright 2018 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +from django.http import StreamingHttpResponse +from drf_yasg.utils import no_body, swagger_auto_schema +from rest_framework import status +from rest_framework.decorators import api_view +from rest_framework.response import Response + +from genericparser.packages.biz.ns_descriptor import NsDescriptor +from genericparser.packages.serializers.create_nsd_info_request import CreateNsdInfoRequestSerializer +from genericparser.packages.serializers.nsd_info import NsdInfoSerializer +from genericparser.packages.serializers.nsd_infos import NsdInfosSerializer +from genericparser.packages.views.common import validate_data +from genericparser.pub.exceptions import GenericparserException +from .common import view_safe_call_with_log + +logger = logging.getLogger(__name__) + + +@swagger_auto_schema( + method='GET', + operation_description="Query a NSD", + request_body=no_body, + responses={ + status.HTTP_200_OK: NsdInfoSerializer(), + status.HTTP_404_NOT_FOUND: 'NSDs do not exist', + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@swagger_auto_schema( + method='DELETE', + operation_description="Delete a NSD", + request_body=no_body, + responses={ + status.HTTP_204_NO_CONTENT: "No content", + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@api_view(http_method_names=['GET', 'DELETE']) +@view_safe_call_with_log(logger=logger) +def ns_info_rd(request, **kwargs): + nsd_info_id = kwargs.get("nsdInfoId") + if request.method == 'GET': + data = NsDescriptor().query_single(nsd_info_id) + nsd_info = validate_data(data, NsdInfoSerializer) + return Response(data=nsd_info.data, status=status.HTTP_200_OK) + if request.method == 'DELETE': + NsDescriptor().delete_single(nsd_info_id) + return Response(status=status.HTTP_204_NO_CONTENT) + + +@swagger_auto_schema( + method='POST', + operation_description="Create a NSD", + request_body=CreateNsdInfoRequestSerializer(), + responses={ + status.HTTP_201_CREATED: NsdInfoSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@swagger_auto_schema( + method='GET', + operation_description="Query multiple NSDs", + request_body=no_body, + responses={ + status.HTTP_200_OK: NsdInfosSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@api_view(http_method_names=['POST', 'GET']) +@view_safe_call_with_log(logger=logger) +def ns_descriptors_rc(request): + if request.method == 'POST': + create_nsd_info_request = validate_data(request.data, CreateNsdInfoRequestSerializer) + data = NsDescriptor().create(create_nsd_info_request.data) + nsd_info = validate_data(data, NsdInfoSerializer) + return Response(data=nsd_info.data, status=status.HTTP_201_CREATED) + + if request.method == 'GET': + nsdId = request.query_params.get("nsdId", None) + data = NsDescriptor().query_multiple(nsdId) + nsd_infos = validate_data(data, NsdInfosSerializer) + return Response(data=nsd_infos.data, status=status.HTTP_200_OK) + + +@swagger_auto_schema( + method='PUT', + operation_description="Upload NSD content", + request_body=no_body, + responses={ + status.HTTP_204_NO_CONTENT: 'PNFD file', + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@swagger_auto_schema( + method='GET', + operation_description="Download NSD content", + request_body=no_body, + responses={ + status.HTTP_204_NO_CONTENT: "No content", + status.HTTP_404_NOT_FOUND: 'NSD does not exist.', + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@api_view(http_method_names=['PUT', 'GET']) +@view_safe_call_with_log(logger=logger) +def nsd_content_ru(request, **kwargs): + nsd_info_id = kwargs.get("nsdInfoId") + if request.method == 'PUT': + files = request.FILES.getlist('file') + try: + local_file_name = NsDescriptor().upload(nsd_info_id, files[0]) + NsDescriptor().parse_nsd_and_save(nsd_info_id, local_file_name) + return Response(data=None, status=status.HTTP_204_NO_CONTENT) + except GenericparserException as e: + NsDescriptor().handle_upload_failed(nsd_info_id) + raise e + except Exception as e: + NsDescriptor().handle_upload_failed(nsd_info_id) + raise e + + if request.method == 'GET': + file_range = request.META.get('RANGE') + file_iterator = NsDescriptor().download(nsd_info_id, file_range) + return StreamingHttpResponse(file_iterator, status=status.HTTP_200_OK) diff --git a/genericparser/packages/views/nsdm_subscription_views.py b/genericparser/packages/views/nsdm_subscription_views.py new file mode 100644 index 0000000..865ece4 --- /dev/null +++ b/genericparser/packages/views/nsdm_subscription_views.py @@ -0,0 +1,259 @@ +# Copyright (C) 2019 Verizon. All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +import traceback + +from drf_yasg.utils import swagger_auto_schema, no_body +from rest_framework import status +from rest_framework.decorators import api_view +from rest_framework.response import Response + +from genericparser.packages.serializers.nsdm_filter_data \ + import NsdmNotificationsFilter +from genericparser.packages.serializers.nsdm_subscription import \ + NsdmSubscriptionsSerializer, \ + NsdmSubscriptionIdSerializer, \ + NsdmSubscriptionSerializer, \ + NsdmSubscriptionRequestSerializer +from genericparser.packages.serializers.response \ + import ProblemDetailsSerializer +from genericparser.pub.exceptions import \ + ResourceNotFoundException, \ + NsdmBadRequestException, NsdmDuplicateSubscriptionException +from genericparser.packages.biz.nsdm_subscription import NsdmSubscription + + +logger = logging.getLogger(__name__) + + +def validate_data(data, serializer): + serialized_data = serializer(data=data) + if not serialized_data.is_valid(): + logger.error('Data validation failed.') + raise NsdmBadRequestException(serialized_data.errors) + return serialized_data + + +def get_problem_details_serializer(title, status_code, error_message): + problem_details = { + "title": title, + "status": status_code, + "detail": error_message + } + problem_details_serializer = ProblemDetailsSerializer(data=problem_details) + problem_details_serializer.is_valid() + return problem_details_serializer + + +@swagger_auto_schema( + method='POST', + operation_description="Create Subscription for NSD Management", + request_body=NsdmSubscriptionRequestSerializer(), + responses={ + status.HTTP_201_CREATED: NsdmSubscriptionSerializer, + status.HTTP_303_SEE_OTHER: ProblemDetailsSerializer(), + status.HTTP_400_BAD_REQUEST: ProblemDetailsSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: ProblemDetailsSerializer() + } +) +@swagger_auto_schema( + method='GET', + operation_description="Query subscriptions for Nsd Management", + request_body=no_body, + responses={ + status.HTTP_200_OK: NsdmSubscriptionsSerializer(), + status.HTTP_400_BAD_REQUEST: ProblemDetailsSerializer(), + status.HTTP_404_NOT_FOUND: ProblemDetailsSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: ProblemDetailsSerializer(), + } +) +@api_view(http_method_names=['POST', 'GET']) +def nsd_subscription_rc(request): + if request.method == 'POST': + logger.debug("SubscribeNotification--post::> %s" % request.data) + try: + title = 'Creating Subscription Failed!' + nsdm_subscription_request = \ + validate_data(request.data, + NsdmSubscriptionRequestSerializer) + subscription = NsdmSubscription().create( + nsdm_subscription_request.data) + subscription_resp = validate_data(subscription, + NsdmSubscriptionSerializer) + return Response(data=subscription_resp.data, + status=status.HTTP_201_CREATED) + except NsdmDuplicateSubscriptionException as e: + logger.error(e.message) + problem_details_serializer = \ + get_problem_details_serializer(title, + status.HTTP_303_SEE_OTHER, + e.message) + return Response(data=problem_details_serializer.data, + status=status.HTTP_303_SEE_OTHER) + except NsdmBadRequestException as e: + problem_details_serializer = \ + get_problem_details_serializer(title, + status.HTTP_400_BAD_REQUEST, + e.message) + return Response(data=problem_details_serializer.data, + status=status.HTTP_400_BAD_REQUEST) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + problem_details_serializer = \ + get_problem_details_serializer( + title, + status.HTTP_500_INTERNAL_SERVER_ERROR, + e.message) + return Response(data=problem_details_serializer.data, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) + if request.method == 'GET': + logger.debug("Subscription Notification GET %s" % request.query_params) + try: + title = 'Query Subscription Failed!' + request_query_params = {} + if request.query_params: + request_query_params = \ + validate_data(request.query_params, + NsdmNotificationsFilter).data + subscription_data = \ + NsdmSubscription().query_multi_subscriptions( + request_query_params) + subscriptions = validate_data(subscription_data, + NsdmSubscriptionsSerializer) + return Response(data=subscriptions.data, status=status.HTTP_200_OK) + except NsdmBadRequestException as e: + logger.error(e.message) + problem_details_serializer = \ + get_problem_details_serializer(title, + status.HTTP_400_BAD_REQUEST, + e.message) + return Response(data=problem_details_serializer.data, + status=status.HTTP_400_BAD_REQUEST) + except ResourceNotFoundException as e: + problem_details_serializer = \ + get_problem_details_serializer(title, + status.HTTP_404_NOT_FOUND, + e.message) + return Response(data=problem_details_serializer.data, + status=status.HTTP_404_NOT_FOUND) + except Exception as e: + logger.error(e.message) + problem_details_serializer = \ + get_problem_details_serializer( + title, + status.HTTP_500_INTERNAL_SERVER_ERROR, + traceback.format_exc()) + return Response(data=problem_details_serializer.data, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + +@swagger_auto_schema( + method='GET', + operation_description="Query subscriptions for Nsd Management", + request_body=no_body, + responses={ + status.HTTP_200_OK: NsdmSubscriptionSerializer(), + status.HTTP_400_BAD_REQUEST: ProblemDetailsSerializer(), + status.HTTP_404_NOT_FOUND: ProblemDetailsSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: ProblemDetailsSerializer() + } +) +@swagger_auto_schema( + method='DELETE', + operation_description="Delete subscription for Nsd Management", + request_body=no_body, + responses={ + status.HTTP_204_NO_CONTENT: 'No_Content', + status.HTTP_400_BAD_REQUEST: ProblemDetailsSerializer(), + status.HTTP_404_NOT_FOUND: ProblemDetailsSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: ProblemDetailsSerializer() + } +) +@api_view(http_method_names=['GET', 'DELETE']) +def nsd_subscription_rd(request, **kwargs): + subscription_id = kwargs.get("subscriptionId") + if request.method == 'GET': + try: + title = 'Query Subscription Failed!' + validate_data({'subscription_id': subscription_id}, + NsdmSubscriptionIdSerializer) + subscription_data = \ + NsdmSubscription().query_single_subscription(subscription_id) + subscription = validate_data(subscription_data, + NsdmSubscriptionSerializer) + return Response(data=subscription.data, status=status.HTTP_200_OK) + except NsdmBadRequestException as e: + logger.error(e.message) + problem_details_serializer = \ + get_problem_details_serializer(title, + status.HTTP_400_BAD_REQUEST, + e.message) + return Response(data=problem_details_serializer.data, + status=status.HTTP_400_BAD_REQUEST) + except ResourceNotFoundException as e: + logger.error(e.message) + problem_details_serializer = \ + get_problem_details_serializer(title, + status.HTTP_404_NOT_FOUND, + e.message) + return Response(data=problem_details_serializer.data, + status=status.HTTP_404_NOT_FOUND) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + problem_details_serializer = \ + get_problem_details_serializer( + title, + status.HTTP_500_INTERNAL_SERVER_ERROR, + "Query of subscriptioni(%s) Failed" + % subscription_id) + return Response(data=problem_details_serializer.data, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) + elif request.method == 'DELETE': + try: + title = 'Delete Subscription Failed!' + validate_data({'subscription_id': subscription_id}, + NsdmSubscriptionIdSerializer) + subscription_data = NsdmSubscription().\ + delete_single_subscription(subscription_id) + return Response(status=status.HTTP_204_NO_CONTENT) + except NsdmBadRequestException as e: + logger.error(e.message) + problem_details_serializer = \ + get_problem_details_serializer(title, + status.HTTP_400_BAD_REQUEST, + e.message) + return Response(data=problem_details_serializer.data, + status=status.HTTP_400_BAD_REQUEST) + except ResourceNotFoundException as e: + logger.error(e.message) + problem_details_serializer = \ + get_problem_details_serializer(title, + status.HTTP_404_NOT_FOUND, + e.message) + return Response(data=problem_details_serializer.data, + status=status.HTTP_404_NOT_FOUND) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + problem_details_serializer = \ + get_problem_details_serializer( + title, + status.HTTP_500_INTERNAL_SERVER_ERROR, + "Delete of subscription(%s) Failed" + % subscription_id) + return Response(data=problem_details_serializer.data, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) diff --git a/genericparser/packages/views/pnf_descriptor_views.py b/genericparser/packages/views/pnf_descriptor_views.py new file mode 100644 index 0000000..e82374f --- /dev/null +++ b/genericparser/packages/views/pnf_descriptor_views.py @@ -0,0 +1,173 @@ +# Copyright 2018 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +from django.http import StreamingHttpResponse +from drf_yasg.utils import no_body, swagger_auto_schema +from rest_framework import status +from rest_framework.decorators import api_view +from rest_framework.response import Response + +from genericparser.packages.biz.pnf_descriptor import PnfDescriptor +from genericparser.packages.serializers.create_pnfd_info_request import CreatePnfdInfoRequestSerializer +from genericparser.packages.serializers.pnfd_info import PnfdInfoSerializer +from genericparser.packages.serializers.pnfd_infos import PnfdInfosSerializer +from genericparser.packages.views.common import validate_data +from genericparser.pub.exceptions import GenericparserException +from genericparser.packages.serializers.genericparser_serializers import ParseModelRequestSerializer +from genericparser.packages.serializers.genericparser_serializers import ParseModelResponseSerializer +from genericparser.packages.serializers.genericparser_serializers import InternalErrorRequestSerializer +from genericparser.pub.utils.syscomm import fun_name +from genericparser.pub.utils.values import ignore_case_get +from .common import view_safe_call_with_log + +logger = logging.getLogger(__name__) + + +@swagger_auto_schema( + method='GET', + operation_description="Query a PNFD", + request_body=no_body, + responses={ + status.HTTP_200_OK: PnfdInfoSerializer(), + status.HTTP_404_NOT_FOUND: "PNFD does not exist", + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@swagger_auto_schema( + method='DELETE', + operation_description="Delete a PNFD", + request_body=no_body, + responses={ + status.HTTP_204_NO_CONTENT: "No content", + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@api_view(http_method_names=['GET', 'DELETE']) +@view_safe_call_with_log(logger=logger) +def pnfd_info_rd(request, **kwargs): # TODO + pnfd_info_id = kwargs.get('pnfdInfoId') + if request.method == 'GET': + logger.debug("Query an individual PNF descriptor> %s" % request.data) + data = PnfDescriptor().query_single(pnfd_info_id) + pnfd_info = validate_data(data, PnfdInfoSerializer) + return Response(data=pnfd_info.data, status=status.HTTP_200_OK) + + if request.method == 'DELETE': + logger.debug("Delete an individual PNFD resource> %s" % request.data) + PnfDescriptor().delete_single(pnfd_info_id) + return Response(data=None, status=status.HTTP_204_NO_CONTENT) + + +@swagger_auto_schema( + method='POST', + operation_description="Create a PNFD", + request_body=CreatePnfdInfoRequestSerializer(), + responses={ + status.HTTP_201_CREATED: PnfdInfoSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@swagger_auto_schema( + method='GET', + operation_description="Query multiple PNFDs", + request_body=no_body, + responses={ + status.HTTP_200_OK: PnfdInfosSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@api_view(http_method_names=['POST', 'GET']) +@view_safe_call_with_log(logger=logger) +def pnf_descriptors_rc(request): + if request.method == 'POST': + create_pnfd_info_request = validate_data(request.data, CreatePnfdInfoRequestSerializer) + data = PnfDescriptor().create(create_pnfd_info_request.data) + pnfd_info = validate_data(data, PnfdInfoSerializer) + return Response(data=pnfd_info.data, status=status.HTTP_201_CREATED) + + if request.method == 'GET': + pnfdId = request.query_params.get('pnfdId', None) + if pnfdId: + data = PnfDescriptor().query_multiple(pnfdId) + else: + data = PnfDescriptor().query_multiple() + pnfd_infos = validate_data(data, PnfdInfosSerializer) + return Response(data=pnfd_infos.data, status=status.HTTP_200_OK) + + +@swagger_auto_schema( + method='PUT', + operation_description="Upload PNFD content", + request_body=no_body, + responses={ + status.HTTP_204_NO_CONTENT: "No content", + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@swagger_auto_schema( + method='GET', + operation_description="Fetch PNFD content", + request_body=no_body, + responses={ + status.HTTP_204_NO_CONTENT: 'PNFD file', + status.HTTP_404_NOT_FOUND: "PNFD does not exist", + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@api_view(http_method_names=['PUT', 'GET']) +@view_safe_call_with_log(logger=logger) +def pnfd_content_ru(request, **kwargs): + pnfd_info_id = kwargs.get("pnfdInfoId") + if request.method == 'PUT': + files = request.FILES.getlist('file') + try: + local_file_name = PnfDescriptor().upload(files[0], pnfd_info_id) + PnfDescriptor().parse_pnfd_and_save(pnfd_info_id, local_file_name) + return Response(data=None, status=status.HTTP_204_NO_CONTENT) + except GenericparserException as e: + PnfDescriptor().handle_upload_failed(pnfd_info_id) + raise e + except Exception as e: + PnfDescriptor().handle_upload_failed(pnfd_info_id) + raise e + + if request.method == 'GET': + file_iterator = PnfDescriptor().download(pnfd_info_id) + return StreamingHttpResponse(file_iterator, status=status.HTTP_200_OK) + + +@swagger_auto_schema( + method='POST', + operation_description="Parse PNF model", + request_body=ParseModelRequestSerializer, + responses={ + status.HTTP_202_ACCEPTED: ParseModelResponseSerializer, + status.HTTP_500_INTERNAL_SERVER_ERROR: InternalErrorRequestSerializer}) +@api_view(http_method_names=['POST']) +def pnf_model_parser(request, *args, **kwargs): + csar_id = ignore_case_get(request.data, "csarId") + inputs = ignore_case_get(request.data, "inputs") + logger.debug( + "Enter %s, csar_id=%s, inputs=%s", + fun_name(), + csar_id, + inputs) + ret = PnfDescriptor().parse_pnfd(csar_id, inputs) + logger.info("Leave %s, Return value is %s", fun_name(), ret) + if ret[0] != 0: + return Response(data={'error': ret[1]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + response = validate_data(ret[1], ParseModelResponseSerializer) + return Response(data=response.data, status=status.HTTP_202_ACCEPTED) diff --git a/genericparser/packages/views/vnf_package_artifact_views.py b/genericparser/packages/views/vnf_package_artifact_views.py new file mode 100644 index 0000000..a6d57f8 --- /dev/null +++ b/genericparser/packages/views/vnf_package_artifact_views.py @@ -0,0 +1,54 @@ +# Copyright (C) 2019 Verizon. All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +from drf_yasg.utils import swagger_auto_schema +from rest_framework import status +from rest_framework.views import APIView +from django.http import FileResponse + +from genericparser.packages.serializers.response import ProblemDetailsSerializer +from genericparser.packages.biz.vnf_pkg_artifacts import FetchVnfPkgArtifact +from .common import view_safe_call_with_log + +logger = logging.getLogger(__name__) + +VALID_FILTERS = [ + "callbackUri", + "notificationTypes", + "vnfdId", + "vnfPkgId", + "operationalState", + "usageState" +] + + +class FetchVnfPkgmArtifactsView(APIView): + + @swagger_auto_schema( + responses={ + status.HTTP_200_OK: None, + status.HTTP_404_NOT_FOUND: ProblemDetailsSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: ProblemDetailsSerializer() + } + ) + @view_safe_call_with_log(logger=logger) + def get(self, request, vnfPkgId, artifactPath): + logger.debug("FetchVnfPkgmArtifactsView--get::> ") + + resp_data = FetchVnfPkgArtifact().fetch(vnfPkgId, artifactPath) + response = FileResponse(resp_data) + + return response diff --git a/genericparser/packages/views/vnf_package_subscription_views.py b/genericparser/packages/views/vnf_package_subscription_views.py new file mode 100644 index 0000000..897b43c --- /dev/null +++ b/genericparser/packages/views/vnf_package_subscription_views.py @@ -0,0 +1,161 @@ +# Copyright (C) 2019 Verizon. All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import traceback +import logging + +from drf_yasg.utils import swagger_auto_schema +from rest_framework import status +from rest_framework.views import APIView +from rest_framework.response import Response + +from genericparser.packages.serializers.vnf_pkg_subscription import PkgmSubscriptionRequestSerializer, \ + PkgmSubscriptionSerializer, PkgmSubscriptionsSerializer +from genericparser.packages.serializers.response import ProblemDetailsSerializer +from genericparser.packages.biz.vnf_pkg_subscription import CreateSubscription, QuerySubscription, TerminateSubscription +from genericparser.packages.views.common import validate_data +from genericparser.pub.exceptions import VnfPkgDuplicateSubscriptionException, VnfPkgSubscriptionException, \ + SubscriptionDoesNotExistsException + +logger = logging.getLogger(__name__) +VALID_FILTERS = ["callbackUri", "notificationTypes", "vnfdId", "vnfPkgId", "operationalState", "usageState"] + + +def get_problem_details_serializer(status_code, error_message): + problem_details = { + "status": status_code, + "detail": error_message + } + problem_details_serializer = ProblemDetailsSerializer(data=problem_details) + problem_details_serializer.is_valid() + return problem_details_serializer + + +class CreateQuerySubscriptionView(APIView): + + @swagger_auto_schema( + request_body=PkgmSubscriptionRequestSerializer, + responses={ + status.HTTP_201_CREATED: PkgmSubscriptionSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } + ) + def post(self, request): + logger.debug("Create VNF package Subscription> %s" % request.data) + try: + vnf_pkg_subscription_request = validate_data(request.data, PkgmSubscriptionRequestSerializer) + data = CreateSubscription(vnf_pkg_subscription_request.data).do_biz() + subscription_info = validate_data(data, PkgmSubscriptionSerializer) + return Response(data=subscription_info.data, status=status.HTTP_201_CREATED) + except VnfPkgDuplicateSubscriptionException as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + problem_details_serializer = get_problem_details_serializer(status.HTTP_303_SEE_OTHER, + traceback.format_exc()) + return Response(data=problem_details_serializer.data, status=status.HTTP_303_SEE_OTHER) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + problem_details_serializer = get_problem_details_serializer(status.HTTP_500_INTERNAL_SERVER_ERROR, + traceback.format_exc()) + return Response(data=problem_details_serializer.data, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + @swagger_auto_schema( + responses={ + status.HTTP_200_OK: PkgmSubscriptionSerializer(), + status.HTTP_400_BAD_REQUEST: ProblemDetailsSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: ProblemDetailsSerializer() + } + ) + def get(self, request): + logger.debug("SubscribeNotification--get::> %s" % request.query_params) + try: + if request.query_params and not set(request.query_params).issubset(set(VALID_FILTERS)): + problem_details_serializer = get_problem_details_serializer(status.HTTP_400_BAD_REQUEST, + "Not a valid filter") + return Response(data=problem_details_serializer.data, status=status.HTTP_400_BAD_REQUEST) + resp_data = QuerySubscription().query_multi_subscriptions(request.query_params) + + subscriptions_serializer = PkgmSubscriptionsSerializer(data=resp_data) + if not subscriptions_serializer.is_valid(): + raise VnfPkgSubscriptionException(subscriptions_serializer.errors) + + return Response(data=subscriptions_serializer.data, status=status.HTTP_200_OK) + + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + problem_details_serializer = get_problem_details_serializer(status.HTTP_500_INTERNAL_SERVER_ERROR, + traceback.format_exc()) + return Response(data=problem_details_serializer.data, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + +class QueryTerminateSubscriptionView(APIView): + + @swagger_auto_schema( + responses={ + status.HTTP_200_OK: PkgmSubscriptionSerializer(), + status.HTTP_404_NOT_FOUND: ProblemDetailsSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: ProblemDetailsSerializer() + } + ) + def get(self, request, subscriptionId): + logger.debug("SubscribeNotification--get::> %s" % subscriptionId) + try: + + resp_data = QuerySubscription().query_single_subscription(subscriptionId) + + subscription_serializer = PkgmSubscriptionSerializer(data=resp_data) + if not subscription_serializer.is_valid(): + raise VnfPkgSubscriptionException(subscription_serializer.errors) + + return Response(data=subscription_serializer.data, status=status.HTTP_200_OK) + except SubscriptionDoesNotExistsException as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + problem_details_serializer = get_problem_details_serializer(status.HTTP_404_NOT_FOUND, + traceback.format_exc()) + return Response(data=problem_details_serializer.data, status=status.HTTP_404_NOT_FOUND) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + problem_details_serializer = get_problem_details_serializer(status.HTTP_500_INTERNAL_SERVER_ERROR, + traceback.format_exc()) + return Response(data=problem_details_serializer.data, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + @swagger_auto_schema( + responses={ + status.HTTP_204_NO_CONTENT: "", + status.HTTP_404_NOT_FOUND: ProblemDetailsSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: ProblemDetailsSerializer() + } + ) + def delete(self, request, subscriptionId): + logger.debug("SubscribeNotification--get::> %s" % subscriptionId) + try: + TerminateSubscription().terminate(subscriptionId) + return Response(status=status.HTTP_204_NO_CONTENT) + except SubscriptionDoesNotExistsException as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + problem_details_serializer = get_problem_details_serializer(status.HTTP_404_NOT_FOUND, + traceback.format_exc()) + return Response(data=problem_details_serializer.data, status=status.HTTP_404_NOT_FOUND) + except Exception as e: + logger.error(e.message) + logger.error(traceback.format_exc()) + problem_details_serializer = get_problem_details_serializer(status.HTTP_500_INTERNAL_SERVER_ERROR, + traceback.format_exc()) + return Response(data=problem_details_serializer.data, status=status.HTTP_500_INTERNAL_SERVER_ERROR) diff --git a/genericparser/packages/views/vnf_package_views.py b/genericparser/packages/views/vnf_package_views.py new file mode 100644 index 0000000..91238f9 --- /dev/null +++ b/genericparser/packages/views/vnf_package_views.py @@ -0,0 +1,169 @@ +# Copyright 2018 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging + +from django.http import StreamingHttpResponse +from drf_yasg.utils import swagger_auto_schema, no_body +from rest_framework import status +from rest_framework.decorators import api_view +from rest_framework.response import Response +from genericparser.pub.exceptions import GenericparserException +from genericparser.packages.serializers.upload_vnf_pkg_from_uri_req import UploadVnfPackageFromUriRequestSerializer +from genericparser.packages.serializers.create_vnf_pkg_info_req import CreateVnfPkgInfoRequestSerializer +from genericparser.packages.serializers.vnf_pkg_info import VnfPkgInfoSerializer +from genericparser.packages.serializers.vnf_pkg_infos import VnfPkgInfosSerializer +from genericparser.packages.biz.vnf_package import VnfPackage, VnfPkgUploadThread, parse_vnfd_and_save, handle_upload_failed +from genericparser.packages.views.common import validate_data +from .common import view_safe_call_with_log + +logger = logging.getLogger(__name__) + + +@swagger_auto_schema( + method="GET", + operation_description="Query multiple VNF package resource", + request_body=no_body, + responses={ + status.HTTP_200_OK: VnfPkgInfosSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@swagger_auto_schema( + method="POST", + operation_description="Create an individual VNF package resource", + request_body=CreateVnfPkgInfoRequestSerializer, + responses={ + status.HTTP_201_CREATED: VnfPkgInfoSerializer(), + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@api_view(http_method_names=["GET", "POST"]) +@view_safe_call_with_log(logger=logger) +def vnf_packages_rc(request): + if request.method == 'GET': + logger.debug("Query VNF packages> %s" % request.data) + data = VnfPackage().query_multiple() + vnf_pkg_infos = validate_data(data, VnfPkgInfosSerializer) + return Response(data=vnf_pkg_infos.data, status=status.HTTP_200_OK) + + if request.method == 'POST': + logger.debug("Create VNF package> %s" % request.data) + create_vnf_pkg_info_request = validate_data(request.data, CreateVnfPkgInfoRequestSerializer) + data = VnfPackage().create_vnf_pkg(create_vnf_pkg_info_request.data) + vnf_pkg_info = validate_data(data, VnfPkgInfoSerializer) + return Response(data=vnf_pkg_info.data, status=status.HTTP_201_CREATED) + + +@swagger_auto_schema( + method='PUT', + operation_description="Upload VNF package content", + request_body=no_body, + responses={ + status.HTTP_202_ACCEPTED: "Successfully", + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@swagger_auto_schema( + method="GET", + operation_description="Fetch VNF package content", + request_body=no_body, + responses={ + status.HTTP_200_OK: VnfPkgInfosSerializer(), + status.HTTP_404_NOT_FOUND: "VNF package does not exist", + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@api_view(http_method_names=["PUT", "GET"]) +@view_safe_call_with_log(logger=logger) +def package_content_ru(request, **kwargs): + vnf_pkg_id = kwargs.get("vnfPkgId") + if request.method == "PUT": + logger.debug("Upload VNF package %s" % vnf_pkg_id) + files = request.FILES.getlist('file') + try: + local_file_name = VnfPackage().upload(vnf_pkg_id, files[0]) + parse_vnfd_and_save(vnf_pkg_id, local_file_name) + return Response(None, status=status.HTTP_202_ACCEPTED) + except GenericparserException as e: + handle_upload_failed(vnf_pkg_id) + raise e + except Exception as e: + handle_upload_failed(vnf_pkg_id) + raise e + + if request.method == "GET": + file_range = request.META.get('RANGE') + file_iterator = VnfPackage().download(vnf_pkg_id, file_range) + return StreamingHttpResponse(file_iterator, status=status.HTTP_200_OK) + + +@swagger_auto_schema( + method='POST', + operation_description="Upload VNF package content from uri", + request_body=UploadVnfPackageFromUriRequestSerializer, + responses={ + status.HTTP_202_ACCEPTED: "Successfully", + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@api_view(http_method_names=['POST']) +@view_safe_call_with_log(logger=logger) +def upload_from_uri_c(request, **kwargs): + vnf_pkg_id = kwargs.get("vnfPkgId") + try: + upload_vnf_from_uri_request = validate_data(request.data, UploadVnfPackageFromUriRequestSerializer) + VnfPkgUploadThread(upload_vnf_from_uri_request.data, vnf_pkg_id).start() + return Response(None, status=status.HTTP_202_ACCEPTED) + except GenericparserException as e: + handle_upload_failed(vnf_pkg_id) + raise e + except Exception as e: + handle_upload_failed(vnf_pkg_id) + raise e + + +@swagger_auto_schema( + method='GET', + operation_description="Query an individual VNF package resource", + request_body=no_body, + responses={ + status.HTTP_200_OK: VnfPkgInfoSerializer(), + status.HTTP_404_NOT_FOUND: "VNF package does not exist", + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@swagger_auto_schema( + method='DELETE', + operation_description="Delete an individual VNF package resource", + request_body=no_body, + responses={ + status.HTTP_204_NO_CONTENT: "No content", + status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error" + } +) +@api_view(http_method_names=['GET', 'DELETE']) +@view_safe_call_with_log(logger=logger) +def vnf_package_rd(request, **kwargs): + vnf_pkg_id = kwargs.get("vnfPkgId") + if request.method == 'GET': + logger.debug("Query an individual VNF package> %s" % request.data) + data = VnfPackage().query_single(vnf_pkg_id) + vnf_pkg_info = validate_data(data, VnfPkgInfoSerializer) + return Response(data=vnf_pkg_info.data, status=status.HTTP_200_OK) + + if request.method == 'DELETE': + logger.debug("Delete an individual VNF package> %s" % request.data) + VnfPackage().delete_vnf_pkg(vnf_pkg_id) + return Response(data=None, status=status.HTTP_204_NO_CONTENT) |