Add and read swagger.json file
[vfc/gvnfm/vnflcm.git] / lcm / lcm / nf / vnfs / vnf_create / inst_vnf.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 traceback
17 from threading import Thread
18
19 from lcm.pub.database.models import NfInstModel, JobStatusModel, NfvoRegInfoModel
20 from lcm.pub.exceptions import NFLCMException
21 from lcm.pub.msapi.nfvolcm import vnfd_rawdata_get, apply_grant_to_nfvo, apply_res_to_nfvo
22 from lcm.pub.utils.jobutil import JobUtil
23 from lcm.pub.utils.timeutil import now_time
24 from lcm.pub.utils.values import ignore_case_get
25
26 logger = logging.getLogger(__name__)
27
28
29 class InstVnf(Thread):
30     def __init__(self, data, nf_inst_id, job_id):
31         super(InstVnf, self).__init__()
32         self.data = data
33         self.nf_inst_id = nf_inst_id
34         self.job_id = job_id
35         self.nfvo_inst_id = ''
36         self.vnfm_inst_id = ''
37
38     def run(self):
39         try:
40             self.inst_pre()
41             self.apply_grant()
42             self.create_res()
43             # self.check_res_status(args)
44             # self.wait_inst_finish(args)
45             # self.lcm_notify(args)
46             JobUtil.add_job_status(self.job_id, 100, "Instantiate Vnf success.")
47             is_exist = JobStatusModel.objects.filter(jobid=self.job_id).exists()
48             logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
49         except NFLCMException as e:
50             self.vnf_inst_failed_handle(e.message)
51             # self.rollback(e.message)
52         except:
53             # self.vnf_inst_failed_handle('unexpected exception')
54             logger.error(traceback.format_exc())
55             # self.rollback('unexpected exception')
56
57     def inst_pre(self):
58         vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
59         if not vnf_insts.exists():
60             raise NFLCMException('VNF nf_inst_id is not exist.')
61
62         self.vnfm_inst_id = vnf_insts[0].vnfm_inst_id
63         if vnf_insts[0].instantiationState != 'NOT_INSTANTIATED':
64             raise NFLCMException('VNF instantiationState is not NOT_INSTANTIATED.')
65
66         #get rawdata by vnfd_id
67         ret = vnfd_rawdata_get(vnf_insts[0].vnfdid)
68         if ret[0] != 0:
69             raise NFLCMException("Get vnfd_raw_data failed.")
70         self.vnfd_info = json.JSONDecoder().decode(ret[1])
71         #checkParameterExist
72         for cp in self.data:
73             if cp not in self.vnfd_info:
74                 raise NFLCMException('Input parameter is not defined in vnfd_info.')
75         #get nfvo info
76         JobUtil.add_job_status(self.job_id, 5, 'GET_NFVO_CONNECTION_INFO')
77         self.load_nfvo_config()
78
79         #update NfInstModel
80         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(flavour_id=ignore_case_get(self.data, "flavourId"),
81                                                                     vnf_level=ignore_case_get(self.data, 'instantiationLevelId'),
82                                                                     input_params=ignore_case_get(self.data, 'additionalParams'),
83                                                                     extension=ignore_case_get(self.data, ''),
84                                                                     initallocatedata=self.vnfd_info,
85                                                                     localizationLanguage=ignore_case_get(self.data, 'localizationLanguage'),
86                                                                     lastuptime=now_time())
87
88     def apply_grant(self):
89         logger.info('[NF instantiation] send resource grand request to nfvo start')
90         #self.check_vm_capacity()
91         content_args = {'nfvoInstanceId': self.nfvo_inst_id, 'vnfmInstanceId': self.vnfm_inst_id,
92                         'nfInstanceId': self.nf_inst_id, 'nfDescriptorId': '',
93                         'lifecycleOperation': 'Instantiate', 'jobId': self.job_id, 'addResource': [],
94                         'removeResource': [], 'placementConstraint': [], 'exVimIdList': [], 'additionalParam': {}}
95
96         vdus = self.vnfd_info['vdus']
97         res_index = 1
98         for vdu in vdus:
99             res_def = {'type': 'VDU', 'resourceDefinitionId': str(res_index), 'vduId': vdu['vdu_id'],
100                        'vimid': '', 'tenant': ''}
101             if self.vnfd_info['metadata']['cross_dc']:
102                 res_def['vimid'] = vdu['properties']['location_info']['vimId']
103                 res_def['tenant'] = vdu['properties']['location_info']['tenant']
104             content_args['addResource'].append(res_def)
105             res_index += 1
106         logger.info('content_args=%s' % content_args)
107         resp = apply_grant_to_nfvo(content_args)
108         logger.info("[NF instantiation] get grant response = %s" % resp)
109         if resp[0] != 0:
110             raise NFLCMException('Nf instancing apply grant exception')
111
112         #update_resources_table()
113         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(instantiationState='INSTANTIATED', lastuptime=now_time())
114         JobUtil.add_job_status(self.job_id, 15, 'Nf instancing apply grant finish')
115         logger.info("Nf instancing apply grant finish")
116
117     def create_res(self):
118         logger.info("[NF instantiation] send resource apply request start")
119         content_args = {'nfvoInstanceId': self.nfvo_inst_id, 'vnfmInstanceId': self.vnfm_inst_id,
120                         'nfInstanceId': self.nf_inst_id, 'nfDescriptorId': '',
121                         'lifecycleOperation': 'Instantiate', 'jobId': '',
122                         'allocateData': self.vnfd_info}
123         volumns = ignore_case_get(self.data, "volumn_storages")
124         #call vim driver api
125         #create_volumns(volumns)
126         JobUtil.add_job_status(self.job_id, 35, 'Nf instancing create resource(volumn_storages) finish')
127         # create_networks(self.vnfd_info)
128         JobUtil.add_job_status(self.job_id, 45, 'Nf instancing create resource(networks) finish')
129         # create_vdus(self.vnfd_info)
130         JobUtil.add_job_status(self.job_id, 65, 'Nf instancing create resource(vms) finish')
131
132     def check_res_status(self, args):
133         try:
134             logger.info('check_res_status, args=%s' % args)
135             # CheckResStatusTask(args).do_biz()
136             return {'result': '100', 'msg': 'Nf instancing check resource status finish', 'context': {}}
137         except Exception as e:
138             logger.error('Nf instancing check resource status exception=%s' % e.message)
139             logger.error(traceback.format_exc())
140             return {'result': '255', 'msg': 'Nf instancing check resource status exception', 'context': {}}
141
142     def wait_inst_finish(self, args):
143         try:
144             logger.info('wait_inst_finish, args=%s' % args)
145             # WaitInstFinishTask(args).do_biz()
146             return {'result': '100', 'msg': 'Nf instancing wait finish', 'context': {}}
147         except Exception as e:
148             logger.error('Nf instancing wait exception=%s' % e.message)
149             logger.error(traceback.format_exc())
150             return {'result': '255', 'msg': 'Nf instancing wait exception', 'context': {}}
151
152     def lcm_notify(self, args):
153         try:
154             logger.info('lcm_notify, args=%s' % args)
155             # LcmNotifyTask(args).do_biz()
156             return {'result': '100', 'msg': 'Nf instancing lcm notify finish', 'context': {}}
157         except Exception as e:
158             logger.error('Nf instancing lcm notify exception=%s' % e.message)
159             logger.error(traceback.format_exc())
160             return {'result': '255', 'msg': 'Nf instancing lcm notify exception', 'context': {}}
161
162     def rollback(self, args):
163         try:
164             logger.info('inst_exception, args=%s' % args)
165             # InstExceptionTask(args).do_biz()
166             return {'result': '100', 'msg': 'Nf instancing exception process finish', 'context': {}}
167         except Exception as e:
168             logger.error('Nf instancing exception process exception=%s' % e.message)
169             logger.error(traceback.format_exc())
170             return {'result': '255', 'msg': 'Nf instancing exception process exception', 'context': {}}
171
172     def load_nfvo_config(self):
173         logger.info("[NF instantiation]get nfvo connection info start")
174         reg_info = NfvoRegInfoModel.objects.filter(vnfminstid='vnfm111').first()
175         if reg_info:
176             self.nfvo_inst_id = reg_info.nfvoid
177             logger.info("[NF instantiation] Registered nfvo id is [%s]"%self.nfvo_inst_id)
178         else:
179             raise NFLCMException("Nfvo was not registered")
180         logger.info("[NF instantiation]get nfvo connection info end")
181
182     def vnf_inst_failed_handle(self, error_msg):
183         logger.error('VNF instantiation failed, detail message: %s' % error_msg)
184         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
185         JobUtil.add_job_status(self.job_id, 255, error_msg)
186         # JobUtil.add_job_status(self.job_id, 255, 'VNF instantiation failed, detail message: %s' % error_msg, 0)
187
188