summaryrefslogtreecommitdiffstats
path: root/res/res/resources/views.py
blob: 73799f71fbd00f0858c5bdcd2cba88b6b2ba2c14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# 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 traceback

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

from res.pub.exceptions import VNFRESException
from res.pub.exceptions import NotFoundException
from res.pub.utils.syscomm import fun_name
from res.pub.database.models import NfInstModel
from res.pub.database.models import StorageInstModel
from res.pub.database.models import NetworkInstModel
from res.pub.database.models import VLInstModel
from res.pub.database.models import VNFCInstModel
from res.pub.database.models import VmInstModel
from res.pub.database.models import FlavourInstModel
from res.pub.database.models import SubNetworkInstModel
from res.pub.database.models import CPInstModel
from res.resources.serializers import VolumeInfoSerializer
from res.resources.serializers import CpsInfoSerializer
from res.resources.serializers import SubnetInfoSerializer
from res.resources.serializers import NetworkInfoSerializer
from res.resources.serializers import FlavorInfoSerializer
from res.resources.serializers import VmInfoSerializer
from res.resources.serializers import VnfInfoSerializer
from res.resources.serializers import VnfsInfoSerializer

logger = logging.getLogger(__name__)


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 NotFoundException as e:
                logger.error(e.args[0])
                return make_error_resp(
                    detail=e.args[0],
                    status=status.HTTP_404_NOT_FOUND
                )
            except VNFRESException as e:
                logger.error(e.args[0])
                return make_error_resp(
                    detail=e.args[0],
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
            except Exception as e:
                logger.error(e.args[0])
                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


class getVnf(APIView):
    @swagger_auto_schema(
        responses={
            status.HTTP_200_OK: VnfInfoSerializer(),
            status.HTTP_404_NOT_FOUND: 'Vnf does not exist',
            status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'
        }
    )
    @view_safe_call_with_log(logger=logger)
    def get(self, request, vnfInstanceId):
        logger.debug("[%s]vnf_inst_id=%s", fun_name(), vnfInstanceId)

        vnf_inst = NfInstModel.objects.filter(nfinstid=vnfInstanceId)
        if not vnf_inst:
            raise NotFoundException('Vnf(%s) does not exist' % vnfInstanceId)

        resp_data = fill_resp_data(vnf_inst[0])

        vnf_info_serializer = VnfInfoSerializer(data=resp_data)
        if not vnf_info_serializer.is_valid():
            raise VNFRESException(vnf_info_serializer.errors)

        return Response(
            data=resp_data,
            status=status.HTTP_200_OK
        )


def fill_resp_data(vnf):
    logger.info('Get the StorageInstModel of list')
    storage_inst = StorageInstModel.objects.filter(instid=vnf.nfinstid)
    arr = []
    for s in storage_inst:
        storage = {
            "virtualStorageInstanceId": s.storageid,
            "virtualStorageDescId": s.storagetype,
            "storageResource": {
                "vimId": s.vimid,
                "resourceId": s.resouceid
            }
        }
        arr.append(storage)
    logger.info('Get the VLInstModel of list.')
    vl_inst = VLInstModel.objects.filter(ownerid=vnf.nfinstid)
    vl_arr = []
    for v in vl_inst:
        net = NetworkInstModel.objects.filter(networkid=v.relatednetworkid)
        if not net:
            raise VNFRESException(
                'NetworkInst(%s) does not exist.' %
                v.relatednetworkid)
        v_dic = {
            "virtualLinkInstanceId": v.vlinstanceid,
            "virtualLinkDescId": v.vldid,
            "networkResource": {
                "vimId": net[0].vimid,
                "resourceId": net[0].resouceid
            }
        }
        vl_arr.append(v_dic)
    logger.info('Get VNFCInstModel of list.')
    vnfc_insts = VNFCInstModel.objects.filter(instid=vnf.nfinstid)
    vnfc_arr = []
    for vnfc in vnfc_insts:
        vm = VmInstModel.objects.filter(vmid=vnfc.vmid)
        if not vm:
            raise VNFRESException('VmInst(%s) does not exist.' % vnfc.vmid)
        storage = StorageInstModel.objects.filter(ownerid=vm[0].vmid)
        if not storage:
            raise VNFRESException(
                'StorageInst(%s) does not exist.' %
                vm[0].vmid)
        vnfc_dic = {
            "vnfcInstanceId": vnfc.vnfcinstanceid,
            "vduId": vnfc.vduid,
            "computeResource": {
                "vimId": vm[0].vimid,
                "resourceId": vm[0].resouceid
            },
            "storageResourceIds": [s.storageid for s in storage]
        }
        vnfc_arr.append(vnfc_dic)
    logger.info('Get the VimInstModel of list.')
    vms = VmInstModel.objects.filter(instid=vnf.nfinstid)
    vm_arr = []
    for vm in vms:
        vm_dic = {
            "vmid": vm.vmid,
            "vimid": vm.vimid,
            "tenant": vm.tenant,
            "resouceid": vm.resouceid,
            "vmname": vm.vmname,
            "nic_array": vm.nic_array,
            "metadata": vm.metadata,
            "volume_array": vm.volume_array,
            "server_group": vm.server_group,
            "availability_zone": vm.availability_zone,
            "flavor_id": vm.flavor_id,
            "security_groups": vm.security_groups,
            "operationalstate": vm.operationalstate,
            "insttype": vm.insttype,
            "is_predefined": vm.is_predefined,
            "create_time": vm.create_time,
            "instid": vm.instid,
            "nodeId": vm.nodeId
        }
        vm_arr.append(vm_dic)

    resp_data = {
        "vnfInstanceId": vnf.nfinstid,
        "vnfInstanceName": vnf.nf_name,
        "vnfInstanceDescription": vnf.nf_desc,
        "onboardedVnfPkgInfoId": vnf.package_id,
        "vnfdId": vnf.vnfdid,
        "vnfdVersion": vnf.version,
        "vnfSoftwareVersion": vnf.vnfSoftwareVersion,
        "vnfProvider": vnf.vendor,
        "vnfProductName": vnf.netype,
        "vnfConfigurableProperties": vnf.vnfConfigurableProperties,
        "instantiationState": vnf.status,
        "instantiatedVnfInfo": {
            "flavourId": vnf.flavour_id,
            "vnfState": vnf.status,
            "scaleStatus": [],
            "extCpInfo": [],
            "extVirtualLink": [],
            "monitoringParameters": {},
            "localizationLanguage": vnf.localizationLanguage,
            "vmInfo": vm_arr,
            "vnfcResourceInfo": vnfc_arr,
            "virtualLinkResourceInfo": vl_arr,
            "virtualStorageResourceInfo": arr
        },
        "metadata": vnf.input_params,
        "extensions": vnf.vnfd_model
    }
    return resp_data


class getVnfs(APIView):
    @swagger_auto_schema(
        responses={
            status.HTTP_200_OK: VnfsInfoSerializer(),
            status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'
        }
    )
    @view_safe_call_with_log(logger=logger)
    def get(self, request):
        logger.debug("Query all the vnfs[%s]", fun_name())

        vnf_insts = NfInstModel.objects.all()
        arr = [fill_resp_data(vnf_inst) for vnf_inst in vnf_insts]

        vnfs_info_serializer = VnfsInfoSerializer(data={'resp_data': arr})
        if not vnfs_info_serializer.is_valid():
            raise VNFRESException(vnfs_info_serializer.errors)

        return Response(
            data={'resp_data': arr},
            status=status.HTTP_200_OK
        )


class getVms(APIView):
    @swagger_auto_schema(
        responses={
            status.HTTP_200_OK: VmInfoSerializer(),
            status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'
        }
    )
    @view_safe_call_with_log(logger=logger)
    def get(self, request, vnfInstanceId):
        logger.debug("Query all the vms by vnfInstanceId[%s]", fun_name())

        vms = VmInstModel.objects.filter(instid=vnfInstanceId)
        arr = [fill_vms_data(vm) for vm in vms]

        vm_info_serializer = VmInfoSerializer(data={'resp_data': arr})
        if not vm_info_serializer.is_valid():
            raise VNFRESException(vm_info_serializer.errors)

        return Response(
            data={'resp_data': arr},
            status=status.HTTP_200_OK
        )


def fill_vms_data(vm):
    vms_data = {
        "vmid": vm.vmid,
        "vimid": vm.vimid,
        "resouceid": vm.resouceid,
        "insttype": vm.insttype,
        "instid": vm.instid,
        "vmname": vm.vmname,
        "operationalstate": vm.operationalstate,
        "tenant": vm.tenant,
        "is_predefined": vm.is_predefined,
        "security_groups": vm.security_groups,
        "flavor_id": vm.flavor_id,
        "availability_zone": vm.availability_zone,
        "server_group": vm.server_group,
        "volume_array": vm.volume_array,
        "metadata": vm.metadata,
        "nic_array": vm.nic_array
    }
    return vms_data


class getFlavors(APIView):
    @swagger_auto_schema(
        responses={
            status.HTTP_200_OK: FlavorInfoSerializer(),
            status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'
        }
    )
    @view_safe_call_with_log(logger=logger)
    def get(self, request, vnfInstanceId):
        logger.debug("Query all the flavors by vnfInstanceId[%s]", fun_name())

        flavours = FlavourInstModel.objects.filter(instid=vnfInstanceId)
        arr = [fill_flavours_data(flavour) for flavour in flavours]

        flavor_info_serializer = FlavorInfoSerializer(data={'resp_data': arr})
        if not flavor_info_serializer.is_valid():
            raise VNFRESException(flavor_info_serializer.errors)

        return Response(
            data=flavor_info_serializer.data,
            status=status.HTTP_200_OK
        )


def fill_flavours_data(f):
    flavours_data = {
        "flavourid": f.flavourid,
        "name": f.name,
        "vcpu": f.vcpu,
        "memory": f.memory,
        "extraspecs": f.extraspecs,
        "instid": f.instid,
        "tenant": f.tenant,
        "vimid": f.vimid,
        "resouceid": f.resouceid,
        "create_time": f.create_time
    }
    return flavours_data


class getNetworks(APIView):
    @swagger_auto_schema(
        responses={
            status.HTTP_200_OK: NetworkInfoSerializer(),
            status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'
        }
    )
    @view_safe_call_with_log(logger=logger)
    def get(self, request, vnfInstanceId):
        logger.debug("Query all the networks by vnfInstanceId[%s]", fun_name())

        networks = NetworkInstModel.objects.filter(instid=vnfInstanceId)
        arr = [fill_networks_data(network) for network in networks]

        network_info_serializer = NetworkInfoSerializer(data={'resp_data': arr})
        if not network_info_serializer.is_valid():
            raise VNFRESException(network_info_serializer.errors)

        return Response(
            data=network_info_serializer.data,
            status=status.HTTP_200_OK
        )


def fill_networks_data(network):
    networks_data = {
        "networkid": network.networkid,
        "vimid": network.vimid,
        "resouceid": network.resouceid,
        "insttype": network.insttype,
        "instid": network.instid,
        "name": network.name
    }
    return networks_data


class getSubnets(APIView):
    @swagger_auto_schema(
        responses={
            status.HTTP_200_OK: SubnetInfoSerializer(),
            status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'
        }
    )
    @view_safe_call_with_log(logger=logger)
    def get(self, request, vnfInstanceId):
        logger.debug("Query all the subnets by vnfInstanceId[%s]", fun_name())

        subnets = SubNetworkInstModel.objects.filter(instid=vnfInstanceId)
        arr = [fill_subnets_data(subnet) for subnet in subnets]

        subnet_info_serializer = SubnetInfoSerializer(data={'resp_data': arr})
        if not subnet_info_serializer.is_valid():
            raise VNFRESException(subnet_info_serializer.errors)

        return Response(
            data=subnet_info_serializer.data,
            status=status.HTTP_200_OK
        )


def fill_subnets_data(subnet):
    subnets_data = {
        "subnetworkid": subnet.subnetworkid,
        "vimid": subnet.vimid,
        "resouceid": subnet.resouceid,
        "networkid": subnet.networkid,
        "insttype": subnet.insttype,
        "instid": subnet.instid,
        "name": subnet.name,
        "cidr": subnet.cidr
    }
    return subnets_data


class getCps(APIView):
    @swagger_auto_schema(
        responses={
            status.HTTP_200_OK: CpsInfoSerializer(),
            status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'
        }
    )
    @view_safe_call_with_log(logger=logger)
    def get(self, request, vnfInstanceId):
        logger.debug("Query all the cps by vnfInstanceId[%s]", fun_name())

        cps = CPInstModel.objects.filter(ownerid=vnfInstanceId)
        arr = [fill_cps_data(cp) for cp in cps]

        cp_info_serializer = CpsInfoSerializer(data={'resp_data': arr})
        if not cp_info_serializer.is_valid():
            raise VNFRESException(cp_info_serializer.errors)

        return Response(
            data=cp_info_serializer.data,
            status=status.HTTP_200_OK
        )


def fill_cps_data(cp):
    cps_data = {
        "cpinstanceid": cp.cpinstanceid,
        "cpdid": cp.cpdid,
        "cpinstancename": cp.cpinstancename,
        "vlinstanceid": cp.vlinstanceid,
        "ownertype": cp.ownertype,
        "ownerid": cp.ownerid,
        "relatedtype": cp.relatedtype
    }
    return cps_data


class getVolumes(APIView):
    @swagger_auto_schema(
        responses={
            status.HTTP_200_OK: VolumeInfoSerializer(),
            status.HTTP_500_INTERNAL_SERVER_ERROR: 'internal error'
        }
    )
    @view_safe_call_with_log(logger=logger)
    def get(self, request, vnfInstanceId):
        logger.debug("Query all the volumes by vnfInstanceId[%s]", fun_name())

        volumes = StorageInstModel.objects.filter(instid=vnfInstanceId)
        arr = [fill_volumes_data(v) for v in volumes]

        volume_serializer = VolumeInfoSerializer(data={'resp_data': arr})
        if not volume_serializer.is_valid():
            raise VNFRESException(volume_serializer.errors)

        return Response(
            data=volume_serializer.data,
            status=status.HTTP_200_OK
        )


def fill_volumes_data(v):
    volumes_data = {
        "storageid": v.storageid,
        "vimid": v.vimid,
        "resouceid": v.resouceid,
        "insttype": v.insttype,
        "instid": v.instid,
        "storagetype": v.storagetype,
        "size": v.size
    }
    return volumes_data