Add vfc-vnfres getNetworks auto-swagger
[vfc/gvnfm/vnfres.git] / res / res / resources / views.py
1 # Copyright 2017 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 drf_yasg.utils import swagger_auto_schema
19 from rest_framework import status
20 from rest_framework.decorators import api_view
21 from rest_framework.response import Response
22 from rest_framework.views import APIView
23
24 from res.pub.database.models import NfInstModel, StorageInstModel, NetworkInstModel, VLInstModel, \
25     VNFCInstModel, VmInstModel, FlavourInstModel, SubNetworkInstModel, CPInstModel
26 from res.pub.exceptions import VNFRESException
27 from res.pub.utils.syscomm import fun_name
28 from res.pub.utils.values import ignore_case_get
29 from res.resources.serializers import VolumeInfoSerializer, CpsInfoSerializer, SubnetInfoSerializer, \
30     NetworkInfoSerializer
31
32 logger = logging.getLogger(__name__)
33
34
35 @api_view(http_method_names=['GET'])
36 def get_vnf(request, *args, **kwargs):
37     vnf_inst_id = ignore_case_get(kwargs, "vnfInstanceId")
38     logger.debug("[%s]vnf_inst_id=%s", fun_name(), vnf_inst_id)
39     try:
40         vnf_inst = NfInstModel.objects.filter(nfinstid=vnf_inst_id)
41         if not vnf_inst:
42             return Response(data={'error': 'Vnf(%s) does not exist' % vnf_inst_id}, status=status.HTTP_404_NOT_FOUND)
43         resp_data = fill_resp_data(vnf_inst[0])
44         return Response(data=resp_data, status=status.HTTP_200_OK)
45     except Exception as e:
46         logger.error(e.message)
47         logger.error(traceback.format_exc())
48         return Response(data={'error': 'Failed to get Vnf(%s)' % vnf_inst_id}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
49
50
51 def fill_resp_data(vnf):
52     logger.info('Get the StorageInstModel of list')
53     storage_inst = StorageInstModel.objects.filter(instid=vnf.nfinstid)
54     arr = []
55     for s in storage_inst:
56         storage = {
57             "virtualStorageInstanceId": s.storageid,
58             "virtualStorageDescId": s.storagetype,
59             "storageResource": {
60                 "vimId": s.vimid,
61                 "resourceId": s.resouceid
62             }
63         }
64         arr.append(storage)
65     logger.info('Get the VLInstModel of list.')
66     vl_inst = VLInstModel.objects.filter(ownerid=vnf.nfinstid)
67     vl_arr = []
68     for v in vl_inst:
69         net = NetworkInstModel.objects.filter(networkid=v.relatednetworkid)
70         if not net:
71             raise VNFRESException('NetworkInst(%s) does not exist.' % v.relatednetworkid)
72         v_dic = {
73             "virtualLinkInstanceId": v.vlinstanceid,
74             "virtualLinkDescId": v.vldid,
75             "networkResource": {
76                 "vimId": net[0].vimid,
77                 "resourceId": net[0].resouceid
78             }
79         }
80         vl_arr.append(v_dic)
81     logger.info('Get VNFCInstModel of list.')
82     vnfc_insts = VNFCInstModel.objects.filter(instid=vnf.nfinstid)
83     vnfc_arr = []
84     for vnfc in vnfc_insts:
85         vm = VmInstModel.objects.filter(vmid=vnfc.vmid)
86         if not vm:
87             raise VNFRESException('VmInst(%s) does not exist.' % vnfc.vmid)
88         storage = StorageInstModel.objects.filter(ownerid=vm[0].vmid)
89         if not storage:
90             raise VNFRESException('StorageInst(%s) does not exist.' % vm[0].vmid)
91         vnfc_dic = {
92             "vnfcInstanceId": vnfc.vnfcinstanceid,
93             "vduId": vnfc.vduid,
94             "computeResource": {
95                 "vimId": vm[0].vimid,
96                 "resourceId": vm[0].resouceid
97             },
98             "storageResourceIds": [s.storageid for s in storage]
99         }
100         vnfc_arr.append(vnfc_dic)
101     logger.info('Get the VimInstModel of list.')
102     vms = VmInstModel.objects.filter(instid=vnf.nfinstid)
103     vm_arr = []
104     # The 'vimInfoId' and 'vimId' each value are same
105     for vm in vms:
106         vm_dic = {
107             "vmid": vm.vmid,
108             "vimid": vm.vimid,
109             "tenant": vm.tenant,
110             "resouceid": vm.resouceid,
111             "vmname": vm.vmname,
112             "nic_array": vm.nic_array,
113             "metadata": vm.metadata,
114             "volume_array": vm.volume_array,
115             "server_group": vm.server_group,
116             "availability_zone": vm.availability_zone,
117             "flavor_id": vm.flavor_id,
118             "security_groups": vm.security_groups,
119             "operationalstate": vm.operationalstate,
120             "insttype": vm.insttype,
121             "is_predefined": vm.is_predefined,
122             "create_time": vm.create_time,
123             "instid": vm.instid,
124             "nodeId": vm.nodeId
125         }
126         vm_arr.append(vm_dic)
127
128     resp_data = {
129         "vnfInstanceId": vnf.nfinstid,
130         "vnfInstanceName": vnf.nf_name,
131         "vnfInstanceDescription": vnf.nf_desc,
132         "onboardedVnfPkgInfoId": vnf.package_id,
133         "vnfdId": vnf.vnfdid,
134         "vnfdVersion": vnf.version,
135         "vnfSoftwareVersion": vnf.vnfSoftwareVersion,
136         "vnfProvider": vnf.vendor,
137         "vnfProductName": vnf.netype,
138         "vnfConfigurableProperties": {vnf.vnfConfigurableProperties},
139         "instantiationState": vnf.status,
140         "instantiatedVnfInfo": {
141             "flavourId": vnf.flavour_id,
142             "vnfState": vnf.status,
143             "scaleStatus": [],
144             "extCpInfo": [],
145             "extVirtualLink": [],
146             "monitoringParameters": {},
147             "localizationLanguage": vnf.localizationLanguage,
148             "vmInfo": vm_arr,
149             "vnfcResourceInfo": vnfc_arr,
150             "virtualLinkResourceInfo": vl_arr,
151             "virtualStorageResourceInfo": arr
152         },
153         "metadata": vnf.input_params,
154         "extensions": vnf.vnfd_model
155     }
156     return resp_data
157
158
159 @api_view(http_method_names=['GET'])
160 def get_vnfs(request):
161     logger.debug("Query all the vnfs[%s]", fun_name())
162     try:
163         vnf_insts = NfInstModel.objects.all()
164         if not vnf_insts:
165             return Response(data={'error': 'Vnfs does not exist'}, status=status.HTTP_404_NOT_FOUND)
166         arr = []
167         for vnf_inst in vnf_insts:
168             arr.append(fill_resp_data(vnf_inst))
169         return Response(data={'resp_data': arr}, status=status.HTTP_200_OK)
170     except Exception as e:
171         logger.error(e.message)
172         logger.error(traceback.format_exc())
173         return Response(data={'error': 'Failed to get Vnfs'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
174
175
176 @api_view(http_method_names=['GET'])
177 def get_vms(request, *args, **kwargs):
178     logger.debug("Query all the vms by vnfInstanceId[%s]", fun_name())
179     try:
180         vnf_inst_id = ignore_case_get(kwargs, "vnfInstanceId")
181         vms = VmInstModel.objects.filter(instid=vnf_inst_id)
182         if not vms:
183             return Response(data={'error': 'Vms does not exist'}, status=status.HTTP_404_NOT_FOUND)
184         arr = []
185         for vm in vms:
186             arr.append(fill_vms_data(vm))
187         return Response(data={'resp_data': arr}, status=status.HTTP_200_OK)
188     except Exception as e:
189         logger.error(e.message)
190         logger.error(traceback.format_exc())
191         return Response(data={'error': 'Failed to get Vms'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
192
193
194 def fill_vms_data(vm):
195     vms_data = {
196         "vmid": vm.vmid,
197         "vimid": vm.vimid,
198         "resouceid": vm.resouceid,
199         "insttype": vm.insttype,
200         "instid": vm.instid,
201         "vmname": vm.vmname,
202         "operationalstate": vm.operationalstate,
203         "tenant": vm.tenant,
204         "is_predefined": vm.is_predefined,
205         "security_groups": vm.security_groups,
206         "flavor_id": vm.flavor_id,
207         "availability_zone": vm.availability_zone,
208         "server_group": vm.server_group,
209         "volume_array": vm.volume_array,
210         "metadata": vm.metadata,
211         "nic_array": vm.nic_array
212     }
213     return vms_data
214
215
216 @api_view(http_method_names=['GET'])
217 def get_flavors(request, *args, **kwargs):
218     logger.debug("Query all the flavors by vnfInstanceId[%s]", fun_name())
219     try:
220         vnf_inst_id = ignore_case_get(kwargs, "vnfInstanceId")
221         flavours = FlavourInstModel.objects.filter(instid=vnf_inst_id)
222         if not flavours:
223             return Response(data={'error': 'Flavours does not exist'}, status=status.HTTP_404_NOT_FOUND)
224         arr = []
225         for flavour in flavours:
226             arr.append(fill_flavours_data(flavour))
227         return Response(data={'resp_data': arr}, status=status.HTTP_200_OK)
228     except Exception as e:
229         logger.error(e.message)
230         logger.error(traceback.format_exc())
231         return Response(data={'error': 'Failed to get flavours'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
232
233
234 def fill_flavours_data(f):
235     flavours_data = {
236         "flavourid": f.flavourid,
237         "name": f.name,
238         "vcpu": f.vcpu,
239         "memory": f.memory,
240         "extraspecs": f.extraspecs,
241         "instid": f.instid,
242         "tenant": f.tenant,
243         "vimid": f.vimid,
244         "resouceid": f.resouceid,
245         "create_time": f.create_time
246     }
247     return flavours_data
248
249
250 class getNetworks(APIView):
251     @swagger_auto_schema(
252         responses={
253             status.HTTP_200_OK: NetworkInfoSerializer(),
254             status.HTTP_404_NOT_FOUND: 'Networks does not exist',
255             status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
256     def get(self, request, vnfInstanceId):
257         logger.debug("Query all the networks by vnfInstanceId[%s]", fun_name())
258         try:
259             networks = NetworkInstModel.objects.filter(instid=vnfInstanceId)
260             if not networks:
261                 return Response(data={'error': 'Networks does not exist'}, status=status.HTTP_404_NOT_FOUND)
262             arr = []
263             for network in networks:
264                 arr.append(fill_networks_data(network))
265
266             networkInfoSerializer = NetworkInfoSerializer(data={'resp_data': arr})
267             isValid = networkInfoSerializer.is_valid()
268             if not isValid:
269                 raise Exception(networkInfoSerializer.errors)
270
271             return Response(data=networkInfoSerializer.data, status=status.HTTP_200_OK)
272         except Exception as e:
273             logger.error(e.message)
274             logger.error(traceback.format_exc())
275             return Response(data={'error': 'Failed to get networks'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
276
277
278 def fill_networks_data(network):
279     networks_data = {
280         "networkid": network.networkid,
281         "vimid": network.vimid,
282         "resouceid": network.resouceid,
283         "insttype": network.insttype,
284         "instid": network.instid,
285         "name": network.name
286     }
287     return networks_data
288
289
290 class getSubnets(APIView):
291     @swagger_auto_schema(
292         responses={
293             status.HTTP_200_OK: SubnetInfoSerializer(),
294             status.HTTP_404_NOT_FOUND: 'Subnets does not exist',
295             status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
296     def get(self, request, vnfInstanceId):
297         logger.debug("Query all the subnets by vnfInstanceId[%s]", fun_name())
298         try:
299             subnets = SubNetworkInstModel.objects.filter(instid=vnfInstanceId)
300             if not subnets:
301                 return Response(data={'error': 'Subnets does not exist'}, status=status.HTTP_404_NOT_FOUND)
302             arr = []
303             for subnet in subnets:
304                 arr.append(fill_subnets_data(subnet))
305             subnetInfoSerializer = SubnetInfoSerializer(data={'resp_data': arr})
306             isValid = subnetInfoSerializer.is_valid()
307             if not isValid:
308                 raise Exception(subnetInfoSerializer.errors)
309
310             return Response(data=subnetInfoSerializer.data, status=status.HTTP_200_OK)
311         except Exception as e:
312             logger.error(e.message)
313             logger.error(traceback.format_exc())
314             return Response(data={'error': 'Failed to get subnets'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
315
316
317 def fill_subnets_data(subnet):
318     subnets_data = {
319         "subnetworkid": subnet.subnetworkid,
320         "vimid": subnet.vimid,
321         "resouceid": subnet.resouceid,
322         "networkid": subnet.networkid,
323         "insttype": subnet.insttype,
324         "instid": subnet.instid,
325         "name": subnet.name,
326         "cidr": subnet.cidr
327     }
328     return subnets_data
329
330
331 class getCps(APIView):
332     @swagger_auto_schema(
333         responses={
334             status.HTTP_200_OK: CpsInfoSerializer(),
335             status.HTTP_404_NOT_FOUND: 'Cps does not exist',
336             status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
337     def get(self, request, vnfInstanceId):
338         logger.debug("Query all the cps by vnfInstanceId[%s]", fun_name())
339         try:
340             cps = CPInstModel.objects.filter(ownerid=vnfInstanceId)
341             if not cps:
342                 return Response(data={'error': 'Cps does not exist'}, status=status.HTTP_404_NOT_FOUND)
343             arr = []
344             for cp in cps:
345                 arr.append(fill_cps_data(cp))
346             cpInfoSerializer = CpsInfoSerializer(data={'resp_data': arr})
347             isValid = cpInfoSerializer.is_valid()
348             if not isValid:
349                 raise Exception(cpInfoSerializer.errors)
350
351             return Response(data=cpInfoSerializer.data, status=status.HTTP_200_OK)
352         except Exception as e:
353             logger.error(e.message)
354             logger.error(traceback.format_exc())
355             return Response(data={'error': 'Failed to get cps'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
356
357
358 def fill_cps_data(cp):
359     cps_data = {
360         "cpinstanceid": cp.cpinstanceid,
361         "cpdid": cp.cpdid,
362         "cpinstancename": cp.cpinstancename,
363         "vlinstanceid": cp.vlinstanceid,
364         "ownertype": cp.ownertype,
365         "ownerid": cp.ownerid,
366         "relatedtype": cp.relatedtype
367     }
368     return cps_data
369
370
371 class getVolumes(APIView):
372     @swagger_auto_schema(
373         responses={
374             status.HTTP_200_OK: VolumeInfoSerializer(),
375             status.HTTP_404_NOT_FOUND: 'Volumes does not exist',
376             status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'})
377     def get(self, request, vnfInstanceId):
378         logger.debug("Query all the volumes by vnfInstanceId[%s]", fun_name())
379         try:
380             volumes = StorageInstModel.objects.filter(instid=vnfInstanceId)
381             if not volumes:
382                 return Response(data={'error': 'Volumes does not exist'}, status=status.HTTP_404_NOT_FOUND)
383             arr = []
384             for v in volumes:
385                 arr.append(fill_volumes_data(v))
386             volumeSerializer = VolumeInfoSerializer(data={'resp_data': arr})
387             isValid = volumeSerializer.is_valid()
388             if not isValid:
389                 raise Exception(volumeSerializer.errors)
390
391             return Response(data=volumeSerializer.data, status=status.HTTP_200_OK)
392         except Exception as e:
393             logger.error(e.message)
394             logger.error(traceback.format_exc())
395             return Response(data={'error': 'Failed to get volumes'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
396
397
398 def fill_volumes_data(v):
399     volumes_data = {
400         "storageid": v.storageid,
401         "vimid": v.vimid,
402         "resouceid": v.resouceid,
403         "insttype": v.insttype,
404         "instid": v.instid,
405         "storagetype": v.storagetype,
406         "size": v.size
407     }
408     return volumes_data