1 # Copyright 2017 ZTE Corporation.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 from threading import Thread
19 from lcm.pub.database.models import NfInstModel, JobStatusModel, NfvoRegInfoModel, VmInstModel, VNFCInstModel, \
20 NetworkInstModel, SubNetworkInstModel, VLInstModel, PortInstModel, CPInstModel, StorageInstModel, FlavourInstModel
21 from lcm.pub.exceptions import NFLCMException
22 from lcm.pub.msapi.nfvolcm import vnfd_rawdata_get, apply_grant_to_nfvo, apply_res_to_nfvo
23 from lcm.pub.utils.jobutil import JobUtil
24 from lcm.pub.utils.timeutil import now_time
25 from lcm.pub.utils.values import ignore_case_get
26 from lcm.pub.vimapi import adaptor
28 logger = logging.getLogger(__name__)
31 class InstVnf(Thread):
32 def __init__(self, data, nf_inst_id, job_id):
33 super(InstVnf, self).__init__()
35 self.nf_inst_id = nf_inst_id
37 self.nfvo_inst_id = ''
38 self.vnfm_inst_id = ''
39 self.create_res_result = {
41 'resourceResult': [{'name': 'vm01'}, {'name': 'vm02'}],
47 'computeresource':{'resourceid':'11'},
52 'affectedvirtuallink':[
55 'virtuallinkinstanceid':'',
56 'networkresource':{'resourceid':'1'},
57 'subnetworkresource':{'resourceid':'1'},
58 'virtuallinkdescid': '',
63 'portresource':{'resourceid':'1'},
68 'virtuallinkinstanceid':'22222',
80 self.check_res_status()
81 # self.wait_inst_finish(args)
82 # self.lcm_notify(args)
83 JobUtil.add_job_status(self.job_id, 100, "Instantiate Vnf success.")
84 is_exist = JobStatusModel.objects.filter(jobid=self.job_id).exists()
85 logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
86 except NFLCMException as e:
87 self.vnf_inst_failed_handle(e.message)
88 # self.rollback(e.message)
90 # self.vnf_inst_failed_handle('unexpected exception')
91 logger.error(traceback.format_exc())
92 # self.rollback('unexpected exception')
95 vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
96 if not vnf_insts.exists():
97 raise NFLCMException('VNF nf_inst_id is not exist.')
99 self.vnfm_inst_id = vnf_insts[0].vnfm_inst_id
100 if vnf_insts[0].instantiationState != 'NOT_INSTANTIATED':
101 raise NFLCMException('VNF instantiationState is not NOT_INSTANTIATED.')
103 #get rawdata by vnfd_id
104 ret = vnfd_rawdata_get(vnf_insts[0].vnfdid)
106 raise NFLCMException("Get vnfd_raw_data failed.")
107 self.vnfd_info = json.JSONDecoder().decode(ret[1])
110 if cp not in self.vnfd_info:
111 raise NFLCMException('Input parameter is not defined in vnfd_info.')
113 JobUtil.add_job_status(self.job_id, 5, 'GET_NFVO_CONNECTION_INFO')
114 self.load_nfvo_config()
117 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(flavour_id=ignore_case_get(self.data, "flavourId"),
118 vnf_level=ignore_case_get(self.data, 'instantiationLevelId'),
119 input_params=ignore_case_get(self.data, 'additionalParams'),
120 extension=ignore_case_get(self.data, ''),
121 initallocatedata=self.vnfd_info,
122 localizationLanguage=ignore_case_get(self.data, 'localizationLanguage'),
123 lastuptime=now_time())
125 def apply_grant(self):
126 logger.info('[NF instantiation] send resource grand request to nfvo start')
127 #self.check_vm_capacity()
128 content_args = {'nfvoInstanceId': self.nfvo_inst_id, 'vnfmInstanceId': self.vnfm_inst_id,
129 'nfInstanceId': self.nf_inst_id, 'nfDescriptorId': '',
130 'lifecycleOperation': 'Instantiate', 'jobId': self.job_id, 'addResource': [],
131 'removeResource': [], 'placementConstraint': [], 'exVimIdList': [], 'additionalParam': {}}
133 vdus = self.vnfd_info['vdus']
136 res_def = {'type': 'VDU', 'resourceDefinitionId': str(res_index), 'vduId': vdu['vdu_id'],
137 'vimid': '', 'tenant': ''}
138 if self.vnfd_info['metadata']['cross_dc']:
139 res_def['vimid'] = vdu['properties']['location_info']['vimId']
140 res_def['tenant'] = vdu['properties']['location_info']['tenant']
141 content_args['addResource'].append(res_def)
143 logger.info('content_args=%s' % content_args)
144 resp = apply_grant_to_nfvo(content_args)
145 logger.info("[NF instantiation] get grant response = %s" % resp)
147 raise NFLCMException('Nf instancing apply grant exception')
149 #update_resources_table()
150 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(instantiationState='INSTANTIATED', lastuptime=now_time())
151 JobUtil.add_job_status(self.job_id, 15, 'Nf instancing apply grant finish')
152 logger.info("Nf instancing apply grant finish")
154 def create_res(self):
155 logger.info("[NF instantiation] create resource start")
156 volumns = ignore_case_get(self.data, "volumn_storages")
157 #create_vim_res(data, do_notify, do_rollback)
158 #create_volumns(volumns)
159 JobUtil.add_job_status(self.job_id, 35, 'Nf instancing create resource(volumn_storages) finish')
161 vls = ignore_case_get(self.data, "vls")
162 # create_networks(vls)
163 JobUtil.add_job_status(self.job_id, 55, 'Nf instancing create resource(networks) finish')
165 vdus = ignore_case_get(self.data, "vdus")
167 JobUtil.add_job_status(self.job_id, 75, 'Nf instancing create resource(vms) finish')
169 logger.info("[NF instantiation] create resource end")
171 def check_res_status(self):
172 logger.info("[NF instantiation] confirm all vms are active start")
173 vnfcs = self.create_res_result['resource_result']['affectedvnfc']
175 if 'success' != vnfc['status']:
176 logger.error("VNFC_STATUS_IS_NOT_ACTIVE[vduid=%s]" % vnfc['vduId'])
177 raise NFLCMException(msgid="VNFC_STATUS_IS_NOT_ACTIVE[vduid=%s]", args=vnfc['vduId'])
179 JobUtil.add_job_status(self.job_id, 80, 'SAVE_VNFC_TO_DB')
180 vls = self.create_res_result['resource_result']['affectedvirtuallink']
181 cps = self.create_res_result['resource_result']['affectedcp']
184 if 'failed' == vnfc['status']:
186 compute_resource = vnfc['computeresource']
187 vminst = VmInstModel.objects.filter(resouceid=compute_resource['resourceid']).first()
188 VNFCInstModel.objects.create(
189 vnfcinstanceid=vnfc['vnfcinstanceid'],
191 vdutype=vnfc['vdutype'],
192 nfinstid=self.nf_inst_id,
195 if 'failed' == vl['status']:
197 network_resource = vl['networkresource']
198 subnet_resource = vl['subnetworkresource']
199 networkinst = NetworkInstModel.objects.filter(resouceid=network_resource['resourceid']).first()
200 subnetinst = SubNetworkInstModel.objects.filter(resouceid=subnet_resource['resourceid']).first()
201 VLInstModel.objects.create(
202 vlinstanceid=vl['virtuallinkinstanceid'],
203 vldid=vl['virtuallinkdescid'],
205 ownerid=self.nf_inst_id,
206 relatednetworkid=networkinst.networkid,
207 relatedsubnetworkid=subnetinst.subnetworkid)
210 if 'failed' == cp['status']:
212 port_resource = cp['portresource']
213 portinst = PortInstModel.objects.filter(resouceid=port_resource['resourceid']).first()
214 ttt = portinst.portid
215 CPInstModel.objects.create(
216 cpinstanceid=cp['cpinstanceid'],
219 relatedport=portinst.portid,
220 ownertype=cp['ownertype'],
221 ownerid=cp['ownerid'],
222 vlinstanceid=cp['virtuallinkinstanceid'])
223 # self.add_job(43, 'INST_DPLY_VM_PRGS')
224 logger.info("[NF instantiation] confirm all vms are active end")
226 def wait_inst_finish(self, args):
228 logger.info('wait_inst_finish, args=%s' % args)
229 # WaitInstFinishTask(args).do_biz()
230 return {'result': '100', 'msg': 'Nf instancing wait finish', 'context': {}}
231 except Exception as e:
232 logger.error('Nf instancing wait exception=%s' % e.message)
233 logger.error(traceback.format_exc())
234 return {'result': '255', 'msg': 'Nf instancing wait exception', 'context': {}}
236 def lcm_notify(self, args):
238 logger.info('lcm_notify, args=%s' % args)
239 # LcmNotifyTask(args).do_biz()
240 return {'result': '100', 'msg': 'Nf instancing lcm notify finish', 'context': {}}
241 except Exception as e:
242 logger.error('Nf instancing lcm notify exception=%s' % e.message)
243 logger.error(traceback.format_exc())
244 return {'result': '255', 'msg': 'Nf instancing lcm notify exception', 'context': {}}
246 def rollback(self, args):
248 logger.info('inst_exception, args=%s' % args)
249 # InstExceptionTask(args).do_biz()
250 return {'result': '100', 'msg': 'Nf instancing exception process finish', 'context': {}}
251 except Exception as e:
252 logger.error('Nf instancing exception process exception=%s' % e.message)
253 logger.error(traceback.format_exc())
254 return {'result': '255', 'msg': 'Nf instancing exception process exception', 'context': {}}
256 def load_nfvo_config(self):
257 logger.info("[NF instantiation]get nfvo connection info start")
258 reg_info = NfvoRegInfoModel.objects.filter(vnfminstid='vnfm111').first()
260 self.nfvo_inst_id = reg_info.nfvoid
261 logger.info("[NF instantiation] Registered nfvo id is [%s]"%self.nfvo_inst_id)
263 raise NFLCMException("Nfvo was not registered")
264 logger.info("[NF instantiation]get nfvo connection info end")
266 def vnf_inst_failed_handle(self, error_msg):
267 logger.error('VNF instantiation failed, detail message: %s' % error_msg)
268 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
269 JobUtil.add_job_status(self.job_id, 255, error_msg)
270 # JobUtil.add_job_status(self.job_id, 255, 'VNF instantiation failed, detail message: %s' % error_msg, 0)
272 def do_rollback(self, progress, msgid, args_=None):
273 # logger.info('add job, progress=%s, msgid=%s, args=%s' % (progress, msgid, args_))
275 # adaptor.delete_vim_res(self.inst_resource, self.do_notify_delete)
277 StorageInstModel.objects.filter(instid=self.nf_inst_id).delete()
278 NetworkInstModel.objects.filter(instid=self.nf_inst_id).delete()
279 SubNetworkInstModel.objects.filter(instid=self.nf_inst_id).delete()
280 PortInstModel.objects.filter(instid=self.nf_inst_id).delete()
281 FlavourInstModel.objects.filter(instid=self.nf_inst_id).delete()
282 VmInstModel.objects.filter(instid=self.nf_inst_id).delete()
283 JobUtil.add_job_status(self.job_id, 255, 'Create resource failed')