Refactor code and testcase of gvnfmres
[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 import json
15 import logging
16 import os
17 import traceback
18
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.exceptions import VNFRESException
25 from res.pub.utils.values import ignore_case_get
26 from res.pub.utils.syscomm import fun_name
27 from res.pub.database.models import NfInstModel, StorageInstModel, NetworkInstModel, VLInstModel, \
28     VNFCInstModel, VmInstModel, VimModel, VimUserModel, FlavourInstModel, SubNetworkInstModel, CPInstModel
29
30 logger = logging.getLogger(__name__)
31
32
33 @api_view(http_method_names=['GET'])
34 def get_vnf(request, *args, **kwargs):
35     vnf_inst_id = ignore_case_get(kwargs, "vnfInstanceId")
36     logger.debug("[%s]vnf_inst_id=%s", fun_name(), vnf_inst_id)
37     try:
38         vnf_inst = NfInstModel.objects.filter(nfinstid=vnf_inst_id)
39         if not vnf_inst:
40             return Response(data={'error': 'Vnf(%s) does not exist' % vnf_inst_id}, status=status.HTTP_404_NOT_FOUND)
41         resp_data = fill_resp_data(vnf_inst[0])
42         return Response(data=resp_data, status=status.HTTP_200_OK)
43     except:
44         logger.error(traceback.format_exc())
45         return Response(data={'error': 'Failed to get Vnf(%s)' % vnf_inst_id}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
46
47
48 def fill_resp_data(vnf):
49     logger.info('Get the StorageInstModel of list')
50     storage_inst = StorageInstModel.objects.filter(instid=vnf.nfinstid)
51     arr = []
52     for s in storage_inst:
53         storage = {
54             "virtualStorageInstanceId": s.storageid,
55             "virtualStorageDescId": s.storageDesc,
56             "storageResource": {
57                 "vimId": s.vimid,
58                 "resourceId": s.resouceid
59             }
60         }
61         arr.append(storage)
62     logger.info('Get the VLInstModel of list.')
63     vl_inst = VLInstModel.objects.filter(ownerid=vnf.nfinstid)
64     vl_arr = []
65     for v in vl_inst:
66         net = NetworkInstModel.objects.filter(networkid=v.relatednetworkid)
67         if not net:
68             raise VNFRESException('NetworkInst(%s) does not exist.' % v.relatednetworkid)
69         v_dic = {
70                     "virtualLinkInstanceId": v.vlinstanceid,
71                     "virtualLinkDescId": v.vldid,
72                     "networkResource": {
73                         "vimId": net[0].vimid,
74                         "resourceId": net[0].resouceid
75                     }
76                 }
77         vl_arr.append(v_dic)
78     logger.info('Get VNFCInstModel of list.')
79     vnfc_insts = VNFCInstModel.objects.filter(nfinstid=vnf.nfinstid)
80     vnfc_arr = []
81     for vnfc in vnfc_insts:
82         vm = VmInstModel.objects.filter(vmid=vnfc.vmid)
83         if not vm:
84             raise VNFRESException('VmInst(%s) does not exist.' % vnfc.vmid)
85         storage = StorageInstModel.objects.filter(ownerid=vm[0].vmid)
86         if not storage:
87             raise VNFRESException('StorageInst(%s) does not exist.' % vm[0].vmid)
88         vnfc_dic = {
89                     "vnfcInstanceId": vnfc.vnfcinstanceid,
90                     "vduId": vnfc.vduid,
91                     "computeResource": {
92                         "vimId": vm[0].vimid,
93                         "resourceId": vm[0].resouceid
94                     },
95                     "storageResourceIds": [s.storageid for s in storage]
96         }
97         vnfc_arr.append(vnfc_dic)
98     logger.info('Get the VimInstModel of list.')
99     vms = VmInstModel.objects.filter(instid=vnf.nfinstid)
100     vim_arr = []
101     # The 'vimInfoId' and 'vimId' each value are same
102     for vm in vms:
103         vims = VimModel.objects.filter(vimid=vm.vimid)
104         for vim in vims:
105             vim_users = VimUserModel.objects.filter(vimid=vim.vimid)
106             vim_dic = {
107                     "vimInfoId": vim.vimid,
108                     "vimId": vim.vimid,
109                     "interfaceInfo": {
110                         "vimType": vim.type,
111                         "apiVersion": vim.version,
112                         "protocolType": (vim.apiurl.split(':')[0] if vim.apiurl and vim.apiurl.index(':') else 'http')
113                     },
114                     "accessInfo": {
115                         "tenant": (vim_users[0].defaulttenant if vim_users and vim_users[0].defaulttenant else ''),
116                         "username": (vim_users[0].username if vim_users and vim_users[0].username else ''),
117                         "password": (vim_users[0].password if vim_users and vim_users[0].password else '')
118                     },
119                     "interfaceEndpoint": vim.apiurl
120             }
121             vim_arr.append(vim_dic)
122
123     resp_data = {
124         "vnfInstanceId": vnf.nfinstid,
125         "vnfInstanceName": vnf.nf_name,
126         "vnfInstanceDescription": vnf.nf_desc,
127         "onboardedVnfPkgInfoId": vnf.package_id,
128         "vnfdId": vnf.vnfdid,
129         "vnfdVersion": vnf.version,
130         "vnfSoftwareVersion": vnf.vnfSoftwareVersion,
131         "vnfProvider": vnf.vendor,
132         "vnfProductName": vnf.producttype,
133         "vnfConfigurableProperties": {vnf.vnfConfigurableProperties},
134         "instantiationState": vnf.instantiationState,
135         "instantiatedVnfInfo": {
136             "flavourId": vnf.flavour_id,
137             "vnfState": vnf.status,
138             "scaleStatus": [],
139             "extCpInfo": [],
140             "extVirtualLink": [],
141             "monitoringParameters": {},
142             "localizationLanguage": vnf.localizationLanguage,
143             "vimInfo": vim_arr,
144             "vnfcResourceInfo": vnfc_arr,
145             "virtualLinkResourceInfo": vl_arr,
146             "virtualStorageResourceInfo": arr
147         },
148         "metadata": vnf.input_params,
149         "extensions": vnf.extension
150     }
151     return resp_data
152
153
154 @api_view(http_method_names=['GET'])
155 def get_vnfs(request):
156     logger.debug("Query all the vnfs[%s]", fun_name())
157     try:
158         vnf_insts = NfInstModel.objects.all()
159         if not vnf_insts:
160             return Response(data={'error': 'Vnfs does not exist'}, status=status.HTTP_404_NOT_FOUND)
161         arr = []
162         for vnf_inst in vnf_insts:
163             arr.append(fill_resp_data(vnf_inst))
164         return Response(data={'resp_data': arr}, status=status.HTTP_200_OK)
165     except:
166         logger.error(traceback.format_exc())
167         return Response(data={'error': 'Failed to get Vnfs'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
168
169
170 @api_view(http_method_names=['GET'])
171 def get_vms(request, *args, **kwargs):
172     logger.debug("Query all the vms by vnfInstanceId[%s]", fun_name())
173     try:
174         vnf_inst_id = ignore_case_get(kwargs, "vnfInstanceId")
175         vms = VmInstModel.objects.filter(instid=vnf_inst_id)
176         if not vms:
177             return Response(data={'error': 'Vms does not exist'}, status=status.HTTP_404_NOT_FOUND)
178         arr = []
179         for vm in vms:
180             arr.append(fill_vms_data(vm))
181         return Response(data={'resp_data': arr}, status=status.HTTP_200_OK)
182     except:
183         logger.error(traceback.format_exc())
184         return Response(data={'error': 'Failed to get Vms'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
185
186
187 def fill_vms_data(vm):
188     vms_data = {
189         "vmid": vm.vmid,
190         "vimid": vm.vimid,
191         "resouceid": vm.resouceid,
192         "insttype": vm.insttype,
193         "instid": vm.instid,
194         "vmname": vm.vmname,
195         "operationalstate": vm.operationalstate,
196         "zoneid": vm.zoneid,
197         "tenant": vm.tenant,
198         "hostid": vm.hostid,
199         "detailinfo": vm.detailinfo,
200         "is_predefined": vm.is_predefined
201     }
202     return vms_data
203
204
205 @api_view(http_method_names=['GET'])
206 def get_flavors(request, *args, **kwargs):
207     logger.debug("Query all the flavors by vnfInstanceId[%s]", fun_name())
208     try:
209         vnf_inst_id = ignore_case_get(kwargs, "vnfInstanceId")
210         flavours = FlavourInstModel.objects.filter(instid=vnf_inst_id)
211         if not flavours:
212             return Response(data={'error': 'Flavours does not exist'}, status=status.HTTP_404_NOT_FOUND)
213         arr = []
214         for flavour in flavours:
215             arr.append(fill_flavours_data(flavour))
216         return Response(data={'resp_data': arr}, status=status.HTTP_200_OK)
217     except:
218         logger.error(traceback.format_exc())
219         return Response(data={'error': 'Failed to get flavours'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
220
221
222 def fill_flavours_data(f):
223     flavours_data = {
224         "flavourid": f.flavourid,
225         "name": f.name,
226         "vcpu": f.vcpu,
227         "memory": f.memory,
228         "extraspecs": f.extraspecs,
229         "instid": f.instid,
230         "tenant": f.tenant,
231         "vmid": f.vmid,
232         "create_time": f.create_time
233     }
234     return flavours_data
235
236
237 @api_view(http_method_names=['GET'])
238 def get_networks(request, *args, **kwargs):
239     logger.debug("Query all the networks by vnfInstanceId[%s]", fun_name())
240     try:
241         vnf_inst_id = ignore_case_get(kwargs, "vnfInstanceId")
242         networks = NetworkInstModel.objects.filter(instid=vnf_inst_id)
243         if not networks:
244             return Response(data={'error': 'Networks does not exist'}, status=status.HTTP_404_NOT_FOUND)
245         arr = []
246         for network in networks:
247             arr.append(fill_networks_data(network))
248         return Response(data={'resp_data': arr}, status=status.HTTP_200_OK)
249     except:
250         logger.error(traceback.format_exc())
251         return Response(data={'error': 'Failed to get networks'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
252
253
254 def fill_networks_data(network):
255     networks_data = {
256         "networkid": network.networkid,
257         "vimid": network.vimid,
258         "resouceid": network.resouceid,
259         "insttype": network.insttype,
260         "instid": network.instid,
261         "name": network.name
262         # "tenant": network.tenant,
263         # "is_shared": network.is_shared,
264         # "is_predefined": network.is_predefined,
265         # "desc": network.desc,
266         # "vendor": network.vendor,
267         # "bandwidth": network.bandwidth,
268         # "mtu": network.mtu,
269         # "network_type": network.network_type,
270         # "segmentid": network.segmentid,
271         # "vlantrans": network.vlantrans,
272         # "networkqos": network.networkqos
273     }
274     return networks_data
275
276
277 @api_view(http_method_names=['GET'])
278 def get_subnets(request, *args, **kwargs):
279     logger.debug("Query all the subnets by vnfInstanceId[%s]", fun_name())
280     try:
281         vnf_inst_id = ignore_case_get(kwargs, "vnfInstanceId")
282         subnets = SubNetworkInstModel.objects.filter(instid=vnf_inst_id)
283         if not subnets:
284             return Response(data={'error': 'Subnets does not exist'}, status=status.HTTP_404_NOT_FOUND)
285         arr = []
286         for subnet in subnets:
287             arr.append(fill_subnets_data(subnet))
288         return Response(data={'resp_data': arr}, status=status.HTTP_200_OK)
289     except:
290         logger.error(traceback.format_exc())
291         return Response(data={'error': 'Failed to get subnets'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
292
293
294 def fill_subnets_data(subnet):
295     subnets_data = {
296         "subnetworkid": subnet.subnetworkid,
297         "vimid": subnet.vimid,
298         "resouceid": subnet.resouceid,
299         "networkid": subnet.networkid,
300         "insttype": subnet.insttype,
301         "instid": subnet.instid,
302         "name": subnet.name,
303         "cidr": subnet.cidr
304     }
305     return subnets_data
306
307
308 @api_view(http_method_names=['GET'])
309 def get_cps(request, *args, **kwargs):
310     logger.debug("Query all the cps by vnfInstanceId[%s]", fun_name())
311     try:
312         vnf_inst_id = ignore_case_get(kwargs, "vnfInstanceId")
313         cps = CPInstModel.objects.filter(ownerid=vnf_inst_id)
314         if not cps:
315             return Response(data={'error': 'Cps does not exist'}, status=status.HTTP_404_NOT_FOUND)
316         arr = []
317         for cp in cps:
318             arr.append(fill_cps_data(cp))
319         return Response(data={'resp_data': arr}, status=status.HTTP_200_OK)
320     except:
321         logger.error(traceback.format_exc())
322         return Response(data={'error': 'Failed to get cps'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
323
324
325 def fill_cps_data(cp):
326     cps_data = {
327         "cpinstanceid": cp.cpinstanceid,
328         "cpdid": cp.cpdid,
329         "cpinstancename": cp.cpinstancename,
330         "vlinstanceid": cp.vlinstanceid,
331         "ownertype": cp.ownertype,
332         "ownerid": cp.ownerid,
333         "relatedtype": cp.relatedtype
334     }
335     return cps_data
336
337
338 @api_view(http_method_names=['GET'])
339 def get_volumes(request, *args, **kwargs):
340     logger.debug("Query all the volumes by vnfInstanceId[%s]", fun_name())
341     try:
342         vnf_inst_id = ignore_case_get(kwargs, "vnfInstanceId")
343         volumes = StorageInstModel.objects.filter(instid=vnf_inst_id)
344         if not volumes:
345             return Response(data={'error': 'Volumes does not exist'}, status=status.HTTP_404_NOT_FOUND)
346         arr = []
347         for v in volumes:
348             arr.append(fill_volumes_data(v))
349         return Response(data={'resp_data': arr}, status=status.HTTP_200_OK)
350     except:
351         logger.error(traceback.format_exc())
352         return Response(data={'error': 'Failed to get volumes'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
353
354
355 def fill_volumes_data(v):
356     volumes_data = {
357         "storageid": v.storageid,
358         "vimid": v.vimid,
359         "resouceid": v.resouceid,
360         "insttype": v.insttype,
361         "instid": v.instid,
362         "storagetype": v.storagetype,
363         "size": v.size,
364         "disktype": v.disktype
365     }
366     return volumes_data
367
368
369 class SwaggerJsonView(APIView):
370     def get(self, request):
371         json_file = os.path.join(os.path.dirname(__file__), 'swagger.json')
372         f = open(json_file)
373         json_data = json.JSONDecoder().decode(f.read())
374         f.close()
375         return Response(json_data)