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, NetworkInstModel, \
20 SubNetworkInstModel, PortInstModel, StorageInstModel, FlavourInstModel, VNFCInstModel, VLInstModel, CPInstModel
21 from lcm.pub.exceptions import NFLCMException
22 from lcm.pub.msapi.nfvolcm import vnfd_rawdata_get, apply_grant_to_nfvo, notify_lcm_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 = ''
40 self.inst_resource = {'volumn': [], # [{"vim_id": ignore_case_get(ret, "vim_id")},{}]
47 # self.create_res_result = {
49 # 'resourceResult': [{'name': 'vm01'}, {'name': 'vm02'}],
54 # 'vnfcinstanceid':'1',
55 # 'computeresource':{'resourceid':'11'},
60 # 'affectedvirtuallink':[
62 # 'status': 'success',
63 # 'virtuallinkinstanceid':'',
64 # 'networkresource':{'resourceid':'1'},
65 # 'subnetworkresource':{'resourceid':'1'},
66 # 'virtuallinkdescid': '',
70 # 'status': 'success',
71 # 'portresource':{'resourceid':'1'},
76 # 'virtuallinkinstanceid':'22222',
88 # self.check_res_status()
89 # self.wait_inst_finish(args)
91 JobUtil.add_job_status(self.job_id, 100, "Instantiate Vnf success.")
92 is_exist = JobStatusModel.objects.filter(jobid=self.job_id).exists()
93 logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
94 except NFLCMException as e:
95 self.vnf_inst_failed_handle(e.message)
96 # self.rollback(e.message)
98 self.vnf_inst_failed_handle('unexpected exception')
99 logger.error(traceback.format_exc())
100 # self.rollback('unexpected exception')
103 vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
104 if not vnf_insts.exists():
105 raise NFLCMException('VNF nf_inst_id is not exist.')
107 # self.vnfm_inst_id = vnf_insts[0].vnfm_inst_id
108 if vnf_insts[0].instantiationState != 'NOT_INSTANTIATED':
109 raise NFLCMException('VNF instantiationState is not NOT_INSTANTIATED.')
111 # get rawdata by vnfd_id
112 ret = vnfd_rawdata_get(vnf_insts[0].vnfdid)
114 raise NFLCMException("Get vnfd_raw_data failed.")
115 self.vnfd_info = json.JSONDecoder().decode(ret[1])
116 # checkParameterExist
118 if cp not in self.vnfd_info:
119 raise NFLCMException('Input parameter is not defined in vnfd_info.')
121 JobUtil.add_job_status(self.job_id, 5, 'Get nfvo connection info')
122 self.load_nfvo_config()
125 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).\
126 update(flavour_id=ignore_case_get(self.data, "flavourId"),
127 vnf_level=ignore_case_get(self.data, 'instantiationLevelId'),
128 input_params=ignore_case_get(self.data, 'additionalParams'),
129 extension=ignore_case_get(self.data, ''),
130 initallocatedata=self.vnfd_info,
131 localizationLanguage=ignore_case_get(self.data, 'localizationLanguage'),
132 lastuptime=now_time())
133 JobUtil.add_job_status(self.job_id, 10, 'Nf instancing pre-check finish')
134 logger.info("Nf instancing pre-check finish")
136 def apply_grant(self):
137 logger.info('[NF instantiation] send resource grand request to nfvo start')
138 # self.check_vm_capacity()
139 content_args = {'nfvoInstanceId': self.nfvo_inst_id, 'vnfmInstanceId': self.vnfm_inst_id,
140 'nfInstanceId': self.nf_inst_id, 'nfDescriptorId': '',
141 'lifecycleOperation': 'Instantiate', 'jobId': self.job_id, 'addResource': [],
142 'removeResource': [], 'placementConstraint': [], 'exVimIdList': [], 'additionalParam': {}}
144 vdus = ignore_case_get(self.vnfd_info, "vdus")
147 res_def = {'type': 'VDU',
148 'resourceDefinitionId': str(res_index),
149 'vduId': ignore_case_get(vdu, "vdu_id"),
152 if self.vnfd_info['metadata']['cross_dc']:
153 res_def['vimid'] = vdu['properties']['location_info']['vimId']
154 res_def['tenant'] = vdu['properties']['location_info']['tenant']
155 content_args['addResource'].append(res_def)
157 logger.info('content_args=%s' % content_args)
158 resp = apply_grant_to_nfvo(content_args)
159 logger.info("[NF instantiation] get grant response = %s" % resp)
161 raise NFLCMException('Nf instancing apply grant exception')
163 # update_resources_table()
164 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(instantiationState='INSTANTIATED',
165 lastuptime=now_time())
166 JobUtil.add_job_status(self.job_id, 20, 'Nf instancing apply grant finish')
167 logger.info("Nf instancing apply grant finish")
169 def create_res(self):
170 logger.info("[NF instantiation] create resource start")
171 adaptor.create_vim_res('', self.do_notify, self.do_rollback)
173 JobUtil.add_job_status(self.job_id, 70, '[NF instantiation] create resource finish')
174 logger.info("[NF instantiation] create resource finish")
176 # def check_res_status(self):
177 # logger.info("[NF instantiation] confirm all vms are active start")
178 # vnfcs = self.create_res_result['resource_result']['affectedvnfc']
180 # if 'success' != vnfc['status']:
181 # logger.error("VNFC_STATUS_IS_NOT_ACTIVE[vduid=%s]" % vnfc['vduId'])
182 # raise NFLCMException(msgid="VNFC_STATUS_IS_NOT_ACTIVE[vduid=%s]", args=vnfc['vduId'])
184 # JobUtil.add_job_status(self.job_id, 80, 'SAVE_VNFC_TO_DB')
185 # vls = self.create_res_result['resource_result']['affectedvirtuallink']
186 # cps = self.create_res_result['resource_result']['affectedcp']
189 # if 'failed' == vnfc['status']:
191 # compute_resource = vnfc['computeresource']
192 # vminst = VmInstModel.objects.filter(resouceid=compute_resource['resourceid']).first()
193 # VNFCInstModel.objects.create(
194 # vnfcinstanceid=vnfc['vnfcinstanceid'],
195 # vduid=vnfc['vduid'],
196 # vdutype=vnfc['vdutype'],
197 # nfinstid=self.nf_inst_id,
200 # if 'failed' == vl['status']:
202 # network_resource = vl['networkresource']
203 # subnet_resource = vl['subnetworkresource']
204 # networkinst = NetworkInstModel.objects.filter(resouceid=network_resource['resourceid']).first()
205 # subnetinst = SubNetworkInstModel.objects.filter(resouceid=subnet_resource['resourceid']).first()
206 # VLInstModel.objects.create(
207 # vlinstanceid=vl['virtuallinkinstanceid'],
208 # vldid=vl['virtuallinkdescid'],
210 # ownerid=self.nf_inst_id,
211 # relatednetworkid=networkinst.networkid,
212 # relatedsubnetworkid=subnetinst.subnetworkid)
215 # if 'failed' == cp['status']:
217 # port_resource = cp['portresource']
218 # portinst = PortInstModel.objects.filter(resouceid=port_resource['resourceid']).first()
219 # ttt = portinst.portid
220 # CPInstModel.objects.create(
221 # cpinstanceid=cp['cpinstanceid'],
224 # relatedport=portinst.portid,
225 # ownertype=cp['ownertype'],
226 # ownerid=cp['ownerid'],
227 # vlinstanceid=cp['virtuallinkinstanceid'])
228 # # self.add_job(43, 'INST_DPLY_VM_PRGS')
229 # logger.info("[NF instantiation] confirm all vms are active end")
231 # def wait_inst_finish(self, args):
233 # logger.info('wait_inst_finish, args=%s' % args)
234 # # WaitInstFinishTask(args).do_biz()
235 # return {'result': '100', 'msg': 'Nf instancing wait finish', 'context': {}}
236 # except Exception as e:
237 # logger.error('Nf instancing wait exception=%s' % e.message)
238 # logger.error(traceback.format_exc())
239 # return {'result': '255', 'msg': 'Nf instancing wait exception', 'context': {}}
241 def lcm_notify(self):
242 logger.info('[NF instantiation] send notify request to nfvo start')
243 reg_info = NfvoRegInfoModel.objects.filter(vnfminstid=self.vnfm_inst_id).first()
244 # vm_info = VmInstModel.objects.filter(nfinstid=self.nf_inst_id)
246 # nfs = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
248 # allocate_data = json.loads(nf.initallocatedata)
249 # vmlist = json.loads(nf.predefinedvm)
250 addition_param = {'vmList': vmlist}
252 vnfcs = VNFCInstModel.objects.filter(nfinstid=self.nf_inst_id)
254 compute_resource = {}
256 vm = VmInstModel.objects.filter(vmid=vnfc.vmid)
258 compute_resource = {'vimId': vm[0].vimid, 'resourceId': vm[0].resouceid,
259 'resourceName': vm[0].vmname, 'tenant': vm[0].tenant}
260 affected_vnfc.append(
261 {'vnfcInstanceId': vnfc.vnfcinstanceid, 'vduId': vnfc.vduid, 'changeType': 'added',
262 'computeResource': compute_resource, 'storageResource': [], 'vduType': vnfc.vdutype})
264 vls = VLInstModel.objects.filter(ownerid=self.nf_inst_id)
266 network_resource = {}
268 if vl.relatednetworkid:
269 network = NetworkInstModel.objects.filter(networkid=vl.relatednetworkid)
270 subnet = SubNetworkInstModel.objects.filter(subnetworkid=vl.relatedsubnetworkid)
272 network_resource = {'vimId': network[0].vimid, 'resourceId': network[0].resouceid,
273 'resourceName': network[0].name, 'tenant': network[0].tenant}
275 subnet_resource = {'vimId': subnet[0].vimid, 'resourceId': subnet[0].resouceid,
276 'resourceName': subnet[0].name, 'tenant': subnet[0].tenant}
278 {'virtualLinkInstanceId': vl.vlinstanceid, 'virtualLinkDescId': vl.vldid, 'changeType': 'added',
279 'networkResource': network_resource, 'subnetworkResource': subnet_resource, 'tenant': vl.tenant})
281 vss = StorageInstModel.objects.filter(instid=self.nf_inst_id)
284 {'virtualStorageInstanceId': vs.storageid, 'virtualStorageDescId': '', 'changeType': 'added',
285 'storageResource': {'vimId': vs.vimid, 'resourceId': vs.resouceid,
286 'resourceName': vs.name, 'tenant': vs.tenant}})
290 cps = CPInstModel.objects.filter(ownerid=vnfc.vnfcinstanceid, ownertype=3)
294 port = PortInstModel.objects.filter(portid=cp.relatedport)
296 port_resource = {'vimId': port[0].vimid, 'resourceId': port[0].resouceid,
297 'resourceName': port[0].name, 'tenant': port[0].tenant}
299 {'cPInstanceId': cp.cpinstanceid, 'cpdId': cp.cpdid, 'ownerid': cp.ownerid,
300 'ownertype': cp.ownertype, 'changeType': 'added', 'portResource': port_resource,
301 'virtualLinkInstanceId': cp.vlinstanceid})
303 cps = CPInstModel.objects.filter(ownerid=self.nf_inst_id, ownertype=0)
304 logger.info('vnf_inst_id=%s, cps size=%s' % (self.nf_inst_id, cps.count()))
308 port = PortInstModel.objects.filter(portid=cp.relatedport)
310 port_resource = {'vimId': port[0].vimid, 'resourceId': port[0].resouceid,
311 'resourceName': port[0].name, 'tenant': port[0].tenant}
313 {'cPInstanceId': cp.cpinstanceid, 'cpdId': cp.cpdid, 'ownerid': cp.ownerid, 'ownertype': cp.ownertype,
314 'changeType': 'added', 'portResource': port_resource,
315 'virtualLinkInstanceId': cp.vlinstanceid})
316 # affectedcapacity = {}
317 # reserved_total = allocate_data.get('reserved_total', {})
318 # affectedcapacity['vm'] = str(reserved_total.get('vmnum', 0))
319 # affectedcapacity['vcpu'] = str(reserved_total.get('vcpunum', 0))
320 # affectedcapacity['vMemory'] = str(reserved_total.get('memorysize', 0))
321 # affectedcapacity['port'] = str(reserved_total.get('portnum', 0))
322 # affectedcapacity['localStorage'] = str(reserved_total.get('hdsize', 0))
323 # affectedcapacity['sharedStorage'] = str(reserved_total.get('shdsize', 0))
325 # "vnfdmodule": allocate_data,
326 "additionalParam": addition_param,
327 "nfvoInstanceId": reg_info.nfvoid,
328 "vnfmInstanceId": self.vnfm_inst_id,
329 "status": 'finished',
330 "nfInstanceId": self.nf_inst_id,
331 "operation": 'instantiate',
333 # 'affectedcapacity': affectedcapacity,
334 'affectedService': [],
335 'affectedVnfc': affected_vnfc,
336 'affectedVirtualLink': affected_vl,
337 'affectedVirtualStorage': affected_vs,
338 'affectedCp': affected_cp}
339 logger.info('content_args=%s' % content_args)
341 resp = notify_lcm_to_nfvo(content_args, self.nf_inst_id)
342 logger.info('[NF instantiation] get lcm response %s' % resp)
344 logger.error("notify lifecycle to nfvo failed.[%s]" % resp[1])
345 raise NFLCMException("send notify request to nfvo failed")
346 logger.info('[NF instantiation] send notify request to nfvo end')
348 # def rollback(self, args):
350 # logger.info('inst_exception, args=%s' % args)
351 # # InstExceptionTask(args).do_biz()
352 # return {'result': '100', 'msg': 'Nf instancing exception process finish', 'context': {}}
353 # except Exception as e:
354 # logger.error('Nf instancing exception process exception=%s' % e.message)
355 # logger.error(traceback.format_exc())
356 # return {'result': '255', 'msg': 'Nf instancing exception process exception', 'context': {}}
358 def load_nfvo_config(self):
359 logger.info("[NF instantiation]get nfvo connection info start")
360 reg_info = NfvoRegInfoModel.objects.filter(vnfminstid='vnfm111').first()
362 self.vnfm_inst_id = reg_info.vnfminstid
363 self.nfvo_inst_id = reg_info.nfvoid
364 logger.info("[NF instantiation] Registered nfvo id is [%s]" % self.nfvo_inst_id)
366 raise NFLCMException("Nfvo was not registered")
367 logger.info("[NF instantiation]get nfvo connection info end")
369 def vnf_inst_failed_handle(self, error_msg):
370 logger.error('VNF instantiation failed, detail message: %s' % error_msg)
371 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
372 JobUtil.add_job_status(self.job_id, 255, error_msg)
374 def do_notify(self, res_type, progress, ret):
375 logger.info('creating [%s] resource' % res_type)
376 progress = 20 + int(progress/2) # 20-70
377 if res_type == adaptor.OPT_CREATE_VOLUME:
378 logger.info('Create vloumns!')
379 if ret["returnCode"] == adaptor.RES_NEW: # new create
380 self.inst_resource['volumn'].append({"vim_id": ignore_case_get(ret, "vim_id"),
381 "res_id": ignore_case_get(ret, "res_id")})
382 JobUtil.add_job_status(self.job_id, progress, 'Create vloumns!')
383 StorageInstModel.objects.create(
390 is_predefined=ret["returnCode"],
391 instid=self.nf_inst_id)
392 elif res_type == adaptor.OPT_CREATE_NETWORK:
393 logger.info('Create networks!')
394 if ret["returnCode"] == adaptor.RES_NEW:
395 self.inst_resource['network'].append({"vim_id": ignore_case_get(ret, "vim_id"),
396 "res_id": ignore_case_get(ret, "res_id")})
397 # self.inst_resource['network'].append({"vim_id": "1"}, {"res_id": "2"})
398 JobUtil.add_job_status(self.job_id, progress, 'Create networks!')
399 NetworkInstModel.objects.create(
406 is_predefined=ret["returnCode"],
407 instid=self.nf_inst_id)
408 elif res_type == adaptor.OPT_CREATE_SUBNET:
409 logger.info('Create subnets!')
410 if ret["returnCode"] == adaptor.RES_NEW:
411 self.inst_resource['subnet'].append({"vim_id": ignore_case_get(ret, "vim_id"),
412 "res_id": ignore_case_get(ret, "res_id")})
413 # self.inst_resource['subnet'].append({"vim_id": "1"}, {"res_id": "2"})
414 JobUtil.add_job_status(self.job_id, progress, 'Create subnets!')
415 SubNetworkInstModel.objects.create(
423 is_predefined=ret["returnCode"],
424 instid=self.nf_inst_id)
425 elif res_type == adaptor.OPT_CREATE_PORT:
426 logger.info('Create ports!')
427 if ret["returnCode"] == adaptor.RES_NEW:
428 self.inst_resource['port'].append({"vim_id": ignore_case_get(ret, "vim_id"),
429 "res_id": ignore_case_get(ret, "res_id")})
430 # self.inst_resource['port'].append({"vim_id": "1"}, {"res_id": "2"})
431 JobUtil.add_job_status(self.job_id, progress, 'Create ports!')
432 PortInstModel.objects.create(
441 is_predefined=ret["returnCode"],
442 instid=self.nf_inst_id)
443 elif res_type == adaptor.OPT_CREATE_FLAVOR:
444 logger.info('Create flavors!')
445 if ret["returnCode"] == adaptor.RES_NEW:
446 self.inst_resource['flavor'].append({"vim_id": ignore_case_get(ret, "vim_id"),
447 "res_id": ignore_case_get(ret, "res_id")})
448 # self.inst_resource['flavor'].append({"vim_id": "1"}, {"res_id": "2"})
449 JobUtil.add_job_status(self.job_id, progress, 'Create flavors!')
450 FlavourInstModel.objects.create(
455 is_predefined=ret["returnCode"],
456 instid=self.nf_inst_id)
457 elif res_type == adaptor.OPT_CREATE_VM:
458 logger.info('Create vms!')
459 if ret["returnCode"] == adaptor.RES_NEW:
460 self.inst_resource['vm'].append({"vim_id": ignore_case_get(ret, "vim_id"),
461 "res_id": ignore_case_get(ret, "res_id")})
462 # self.inst_resource['vm'].append({"vim_id": "1"}, {"res_id": "2"})
463 JobUtil.add_job_status(self.job_id, progress, 'Create vms!')
464 VmInstModel.objects.create(
469 instid=self.nf_inst_id,
471 is_predefined=ret["returnCode"],
474 def do_rollback(self, args_=None):
475 logger.error('error info : %s' % args_)
476 adaptor.delete_vim_res(self.inst_resource, self.do_notify_delete)
477 logger.error('rollback resource complete')
479 StorageInstModel.objects.filter(instid=self.nf_inst_id).delete()
480 NetworkInstModel.objects.filter(instid=self.nf_inst_id).delete()
481 SubNetworkInstModel.objects.filter(instid=self.nf_inst_id).delete()
482 PortInstModel.objects.filter(instid=self.nf_inst_id).delete()
483 FlavourInstModel.objects.filter(instid=self.nf_inst_id).delete()
484 VmInstModel.objects.filter(instid=self.nf_inst_id).delete()
485 logger.error('delete table complete')
486 raise NFLCMException("Create resource failed")
488 def do_notify_delete(self, ret):
489 logger.error('Deleting [%s] resource' % ret)