Ns descriptor related stuffs.
[vfc/nfvo/catalog.git] / catalog / packages / views / ns_descriptor_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 logging
16 import traceback
17
18 from django.http import StreamingHttpResponse
19 from catalog.packages.biz.ns_descriptor import create, delete_single, download, query_multiple, query_single, upload
20 from catalog.packages.serializers.create_nsd_info_request import CreateNsdInfoRequestSerializer
21 from catalog.packages.serializers.nsd_info import NsdInfoSerializer
22 from catalog.packages.serializers.nsd_infos import NsdInfosSerializer
23 from catalog.pub.exceptions import CatalogException
24 from drf_yasg.utils import no_body, swagger_auto_schema
25 from rest_framework import status
26 from rest_framework.decorators import api_view
27 from rest_framework.response import Response
28
29 logger = logging.getLogger(__name__)
30
31
32 @swagger_auto_schema(
33     method='GET',
34     operation_description="Query a NSD",
35     request_body=no_body,
36     responses={
37         status.HTTP_200_OK: NsdInfoSerializer(),
38         status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
39     }
40 )
41 @swagger_auto_schema(
42     method='DELETE',
43     operation_description="Delete a NSD",
44     request_body=no_body,
45     responses={
46         status.HTTP_204_NO_CONTENT: None,
47         status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
48     }
49 )
50 @api_view(http_method_names=['GET', 'DELETE'])
51 def ns_info_rd(request, nsdInfoId):   # TODO
52     if request.method == 'GET':
53         try:
54             data = query_single(nsdInfoId)
55             nsd_info = validate_data(data, NsdInfoSerializer)
56             return Response(data=nsd_info.data, status=status.HTTP_200_OK)
57         except CatalogException as e:
58             logger.error(e.message)
59             error_msg = {'error': 'Query of a NSD failed.'}
60         except Exception as e:
61             logger.error(e.message)
62             logger.error(traceback.format_exc())
63             error_msg = {'error': 'Query of a NSD failed.'}
64         return Response(data=error_msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
65
66     if request.method == 'DELETE':
67         try:
68             delete_single(nsdInfoId)
69             return Response(status=status.HTTP_204_NO_CONTENT)
70         except CatalogException as e:
71             logger.error(e.message)
72             error_msg = {'error': 'Deletion of a NSD failed.'}
73         except Exception as e:
74             logger.error(e.message)
75             logger.error(traceback.format_exc())
76             error_msg = {'error': 'Deletion of a NSD failed.'}
77         return Response(data=error_msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
78
79
80 @swagger_auto_schema(
81     method='POST',
82     operation_description="Create a NSD",
83     request_body=CreateNsdInfoRequestSerializer(),
84     responses={
85         status.HTTP_201_CREATED: NsdInfoSerializer(),
86         status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
87     }
88 )
89 @swagger_auto_schema(
90     method='GET',
91     operation_description="Query multiple NSDs",
92     request_body=no_body,
93     responses={
94         status.HTTP_200_OK: NsdInfosSerializer(),
95         status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
96     }
97 )
98 @api_view(http_method_names=['POST', 'GET'])
99 def ns_descriptors_rc(request, *args, **kwargs):
100     if request.method == 'POST':
101         try:
102             create_nsd_info_requst = validate_data(request.data, CreateNsdInfoRequestSerializer)
103             data = create(create_nsd_info_requst.data)
104             nsd_info = validate_data(data, NsdInfoSerializer)
105             return Response(data=nsd_info.data, status=status.HTTP_201_CREATED)
106         except CatalogException as e:
107             logger.error(e.message)
108             error_msg = {'error': 'Creating a NSD failed.'}
109         except Exception as e:
110             logger.error(e.message)
111             logger.error(traceback.format_exc())
112             error_msg = {'error': 'Creating a NSD failed.'}
113         return Response(data=error_msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
114
115     if request.method == 'GET':
116         try:
117             data = query_multiple()
118             nsd_infos = validate_data(data, NsdInfosSerializer)
119             return Response(data=nsd_infos.data, status=status.HTTP_200_OK)
120         except CatalogException as e:
121             logger.error(e.message)
122             error_msg = {'error': 'Query of multiple NSDs failed.'}
123         except Exception as e:
124             logger.error(e.message)
125             logger.error(traceback.format_exc())
126             error_msg = {'error': 'Query of multiple NSDs failed.'}
127         return Response(data=error_msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
128
129
130 @swagger_auto_schema(
131     method='PUT',
132     operation_description="Upload NSD content",
133     request_body=no_body,
134     responses={
135         status.HTTP_204_NO_CONTENT: 'PNFD file',
136         status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
137     }
138 )
139 @swagger_auto_schema(
140     method='GET',
141     operation_description="Download NSD content",
142     request_body=no_body,
143     responses={
144         status.HTTP_204_NO_CONTENT: None,
145         status.HTTP_500_INTERNAL_SERVER_ERROR: "Internal error"
146     }
147 )
148 @api_view(http_method_names=['PUT', 'GET'])
149 def nsd_content_ru(request, *args, **kwargs):
150     nsd_info_id = kwargs.get("nsdInfoId")
151     if request.method == 'PUT':
152         files = request.FILES.getlist('file')
153         try:
154             upload(files[0], nsd_info_id)
155             return Response(data=None, status=status.HTTP_204_NO_CONTENT)
156         except Exception as e:
157             logger.error(e.message)
158             logger.error(traceback.format_exc())
159             error_msg = {'error': 'Uploading NSD content failed.'}
160         return Response(data=error_msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
161
162     if request.method == 'GET':
163         try:
164             file_path, file_name, file_size = download(nsd_info_id)
165             start, end = 0, file_size
166             file_range = request.META.get('RANGE')
167             if file_range:
168                 [start, end] = file_range.split('-')
169                 start, end = start.strip(), end.strip()
170                 start, end = int(start), int(end)
171             response = StreamingHttpResponse(
172                 read_partial_file(file_path, start, end),
173                 status=status.HTTP_200_OK
174             )
175             response['Content-Range'] = '%s-%s' % (start, end)
176             response['Content-Disposition'] = 'attachment; filename=%s' % file_name.encode('utf-8')
177             response['Content-Length'] = end - start
178             return response
179         except Exception as e:
180             logger.error(e.message)
181             logger.error(traceback.format_exc())
182             error_msg = {'error': 'Downloading NSD content failed.'}
183         return Response(data=error_msg, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
184
185
186 def read_partial_file(file_path, start, end):
187     fp = open(file_path, 'rb')
188     fp.seek(start)
189     pos = start
190     CHUNK_SIZE = 1024 * 8
191     while pos + CHUNK_SIZE < end:
192         yield fp.read(CHUNK_SIZE)
193         pos = fp.tell()
194     yield fp.read(end - pos)
195
196
197 def validate_data(data, serializer):
198     serialized_data = serializer(data=data)
199     if not serialized_data.is_valid():
200         logger.error('Data validation failed.')
201         raise CatalogException(serialized_data.error)
202     return serialized_data