Merge "Ns descriptor related stuffs."
[vfc/nfvo/catalog.git] / catalog / packages / views / vnf_package_views.py
1 # Copyright 2018 ZTE Corporation.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import traceback
16 import logging
17 import os
18
19 from catalog.pub.config.config import CATALOG_ROOT_PATH
20 from drf_yasg.utils import swagger_auto_schema, no_body
21 from rest_framework import status
22 from rest_framework.decorators import api_view
23 from rest_framework.response import Response
24 from catalog.pub.exceptions import CatalogException
25 from catalog.packages.serializers.upload_vnf_pkg_from_uri_req import UploadVnfPackageFromUriRequestSerializer
26 from catalog.packages.serializers.create_vnf_pkg_info_req import CreateVnfPkgInfoRequestSerializer
27 from catalog.packages.serializers.vnf_pkg_info import VnfPkgInfoSerializer
28 from catalog.packages.biz.vnf_package import create_vnf_pkg, query_multiple, VnfpkgUploadThread, \
29     query_single, delete_single
30
31 logger = logging.getLogger(__name__)
32
33
34 @swagger_auto_schema(
35     method="GET",
36     operation_description="Query multiple VNF package resource",
37     request_body=no_body,
38     responses={
39         status.HTTP_200_OK: VnfPkgInfoSerializer(),
40         status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
41     }
42 )
43 @swagger_auto_schema(
44     method="POST",
45     operation_description="Create an individual VNF package resource",
46     request_body=CreateVnfPkgInfoRequestSerializer,
47     responses={
48         status.HTTP_201_CREATED: VnfPkgInfoSerializer(),
49         status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
50     }
51 )
52 @api_view(http_method_names=["GET", "POST"])
53 def vnf_packages_rc(request):
54     if request.method == 'GET':
55         logger.debug("Query VNF Packages> %s" % request.data)
56         try:
57             res = query_multiple()
58             query_serializer = VnfPkgInfoSerializer(data=res)
59             if not query_serializer.is_valid():
60                 raise CatalogException
61             return Response(data=query_serializer.data, status=status.HTTP_200_OK)
62         except CatalogException:
63             logger.error(traceback.format_exc())
64             return Response(data={'error': 'Query vnfPkg failed.'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
65         except Exception as e:
66             logger.error(e.message)
67             logger.error(traceback.format_exc())
68             return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
69
70     if request.method == 'POST':
71         logger.debug("CreateVnfPkg> %s" % request.data)
72         try:
73             req_serializer = CreateVnfPkgInfoRequestSerializer(data=request.data)
74             if not req_serializer.is_valid():
75                 raise CatalogException
76             res = create_vnf_pkg(req_serializer.data)
77             create_vnf_pkg_resp_serializer = VnfPkgInfoSerializer(data=res)
78             if not create_vnf_pkg_resp_serializer.is_valid():
79                 raise CatalogException
80             return Response(data=create_vnf_pkg_resp_serializer.data, status=status.HTTP_201_CREATED)
81         except CatalogException:
82             logger.error(traceback.format_exc())
83             return Response(data={'error': 'Create vnfPkg failed.'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
84         except Exception as e:
85             logger.error(e.message)
86             logger.error(traceback.format_exc())
87             return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
88
89
90 @swagger_auto_schema(
91     method='PUT',
92     operation_description="Upload VNF package content",
93     request_body=no_body,
94     responses={
95         status.HTTP_202_ACCEPTED: "Successfully",
96         status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
97     }
98 )
99 @api_view(http_method_names=['PUT'])
100 def upload_vnf_pkg_content(request, vnfPkgId):
101     logger.debug("UploadVnf %s" % vnfPkgId)
102     file_object = request.FILES.get('file')
103     upload_path = os.path.join(CATALOG_ROOT_PATH, vnfPkgId)
104     if not os.path.exists(upload_path):
105         os.makedirs(upload_path, 0o777)
106     try:
107         upload_file_name = os.path.join(upload_path, file_object.name)
108         with open(upload_file_name, 'wb+') as dest_file:
109             for chunk in file_object.chunks():
110                 dest_file.write(chunk)
111     except Exception as e:
112         logger.error("File upload exception.[%s:%s]" % (type(e), str(e)))
113         logger.error("%s", traceback.format_exc())
114     return Response(None, status.HTTP_202_ACCEPTED)
115
116
117 @swagger_auto_schema(
118     method='POST',
119     operation_description="Upload VNF package content from uri",
120     request_body=UploadVnfPackageFromUriRequestSerializer,
121     responses={
122         status.HTTP_202_ACCEPTED: "Successfully",
123         status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
124     }
125 )
126 @api_view(http_method_names=['POST'])
127 def upload_vnf_pkg_from_uri(request, vnfPkgId):
128     try:
129         req_serializer = UploadVnfPackageFromUriRequestSerializer(data=request.data)
130         if not req_serializer.is_valid():
131             raise CatalogException
132         VnfpkgUploadThread(req_serializer.data, vnfPkgId).start()
133         return Response(None, status=status.HTTP_202_ACCEPTED)
134     except CatalogException:
135         logger.error(traceback.format_exc())
136         return Response(data={'error': 'Upload vnfPkg failed.'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
137     except Exception as e:
138         logger.error(e.message)
139         logger.error(traceback.format_exc())
140         return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
141
142
143 @swagger_auto_schema(
144     method='GET',
145     operation_description="Query an individual VNF package resource",
146     request_body=no_body,
147     responses={
148         status.HTTP_200_OK: VnfPkgInfoSerializer(),
149         status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
150     }
151 )
152 @swagger_auto_schema(
153     method='DELETE',
154     operation_description="Delete an individual VNF package resource",
155     request_body=no_body,
156     responses={
157         status.HTTP_204_NO_CONTENT: None,
158         status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
159     }
160 )
161 @api_view(http_method_names=['GET', 'DELETE'])
162 def vnf_package_rd(request, vnfPkgId):
163     if request.method == 'GET':
164         logger.debug("Query an individual VNF package> %s" % request.data)
165         try:
166             res = query_single(vnfPkgId)
167             query_serializer = VnfPkgInfoSerializer(data=res)
168             if not query_serializer.is_valid():
169                 raise CatalogException
170             return Response(data=query_serializer.data, status=status.HTTP_200_OK)
171         except CatalogException:
172             logger.error(traceback.format_exc())
173             return Response(data={'error': 'Query an individual VNF package failed.'},
174                             status=status.HTTP_500_INTERNAL_SERVER_ERROR)
175         except Exception as e:
176             logger.error(e.message)
177             logger.error(traceback.format_exc())
178             return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
179
180     if request.method == 'DELETE':
181         logger.debug("Delete an individual VNF package> %s" % request.data)
182         try:
183             delete_single(vnfPkgId)
184             return Response(data=None, status=status.HTTP_204_NO_CONTENT)
185         except CatalogException:
186             logger.error(traceback.format_exc())
187             return Response(data={'error': 'Delete an individual VNF package failed.'},
188                             status=status.HTTP_500_INTERNAL_SERVER_ERROR)
189         except Exception as e:
190             logger.error(e.message)
191             logger.error(traceback.format_exc())
192             return Response(data={'error': 'unexpected exception'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)