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
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
27 logger = logging.getLogger(__name__)
30 class InstVnf(Thread):
31 def __init__(self, data, nf_inst_id, job_id):
32 super(InstVnf, self).__init__()
34 self.nf_inst_id = nf_inst_id
36 self.nfvo_inst_id = ''
37 self.vnfm_inst_id = ''
38 self.create_res_result = {
40 'resourceResult': [{'name': 'vm01'}, {'name': 'vm02'}],
46 'computeresource':{'resourceid':'11'},
51 'affectedvirtuallink':[
54 'virtuallinkinstanceid':'',
55 'networkresource':{'resourceid':'1'},
56 'subnetworkresource':{'resourceid':'1'},
57 'virtuallinkdescid': '',
62 'portresource':{'resourceid':'1'},
67 'virtuallinkinstanceid':'22222',
79 self.check_res_status()
80 # self.wait_inst_finish(args)
81 # self.lcm_notify(args)
82 JobUtil.add_job_status(self.job_id, 100, "Instantiate Vnf success.")
83 is_exist = JobStatusModel.objects.filter(jobid=self.job_id).exists()
84 logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
85 except NFLCMException as e:
86 self.vnf_inst_failed_handle(e.message)
87 # self.rollback(e.message)
89 # self.vnf_inst_failed_handle('unexpected exception')
90 logger.error(traceback.format_exc())
91 # self.rollback('unexpected exception')
94 vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
95 if not vnf_insts.exists():
96 raise NFLCMException('VNF nf_inst_id is not exist.')
98 self.vnfm_inst_id = vnf_insts[0].vnfm_inst_id
99 if vnf_insts[0].instantiationState != 'NOT_INSTANTIATED':
100 raise NFLCMException('VNF instantiationState is not NOT_INSTANTIATED.')
102 #get rawdata by vnfd_id
103 ret = vnfd_rawdata_get(vnf_insts[0].vnfdid)
105 raise NFLCMException("Get vnfd_raw_data failed.")
106 self.vnfd_info = json.JSONDecoder().decode(ret[1])
109 if cp not in self.vnfd_info:
110 raise NFLCMException('Input parameter is not defined in vnfd_info.')
112 JobUtil.add_job_status(self.job_id, 5, 'GET_NFVO_CONNECTION_INFO')
113 self.load_nfvo_config()
116 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(flavour_id=ignore_case_get(self.data, "flavourId"),
117 vnf_level=ignore_case_get(self.data, 'instantiationLevelId'),
118 input_params=ignore_case_get(self.data, 'additionalParams'),
119 extension=ignore_case_get(self.data, ''),
120 initallocatedata=self.vnfd_info,
121 localizationLanguage=ignore_case_get(self.data, 'localizationLanguage'),
122 lastuptime=now_time())
124 def apply_grant(self):
125 logger.info('[NF instantiation] send resource grand request to nfvo start')
126 #self.check_vm_capacity()
127 content_args = {'nfvoInstanceId': self.nfvo_inst_id, 'vnfmInstanceId': self.vnfm_inst_id,
128 'nfInstanceId': self.nf_inst_id, 'nfDescriptorId': '',
129 'lifecycleOperation': 'Instantiate', 'jobId': self.job_id, 'addResource': [],
130 'removeResource': [], 'placementConstraint': [], 'exVimIdList': [], 'additionalParam': {}}
132 vdus = self.vnfd_info['vdus']
135 res_def = {'type': 'VDU', 'resourceDefinitionId': str(res_index), 'vduId': vdu['vdu_id'],
136 'vimid': '', 'tenant': ''}
137 if self.vnfd_info['metadata']['cross_dc']:
138 res_def['vimid'] = vdu['properties']['location_info']['vimId']
139 res_def['tenant'] = vdu['properties']['location_info']['tenant']
140 content_args['addResource'].append(res_def)
142 logger.info('content_args=%s' % content_args)
143 resp = apply_grant_to_nfvo(content_args)
144 logger.info("[NF instantiation] get grant response = %s" % resp)
146 raise NFLCMException('Nf instancing apply grant exception')
148 #update_resources_table()
149 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(instantiationState='INSTANTIATED', lastuptime=now_time())
150 JobUtil.add_job_status(self.job_id, 15, 'Nf instancing apply grant finish')
151 logger.info("Nf instancing apply grant finish")
153 def create_res(self):
154 logger.info("[NF instantiation] create resource start")
155 volumns = ignore_case_get(self.data, "volumn_storages")
156 #create_vim_res(data, do_notify, do_rollback)
157 #create_volumns(volumns)
158 JobUtil.add_job_status(self.job_id, 35, 'Nf instancing create resource(volumn_storages) finish')
160 vls = ignore_case_get(self.data, "vls")
161 # create_networks(vls)
162 JobUtil.add_job_status(self.job_id, 55, 'Nf instancing create resource(networks) finish')
164 vdus = ignore_case_get(self.data, "vdus")
166 JobUtil.add_job_status(self.job_id, 75, 'Nf instancing create resource(vms) finish')
168 logger.info("[NF instantiation] create resource end")
170 def check_res_status(self):
171 logger.info("[NF instantiation] confirm all vms are active start")
172 vnfcs = self.create_res_result['resource_result']['affectedvnfc']
174 if 'success' != vnfc['status']:
175 logger.error("VNFC_STATUS_IS_NOT_ACTIVE[vduid=%s]" % vnfc['vduId'])
176 raise NFLCMException(msgid="VNFC_STATUS_IS_NOT_ACTIVE[vduid=%s]", args=vnfc['vduId'])
178 JobUtil.add_job_status(self.job_id, 80, 'SAVE_VNFC_TO_DB')
179 vls = self.create_res_result['resource_result']['affectedvirtuallink']
180 cps = self.create_res_result['resource_result']['affectedcp']
183 if 'failed' == vnfc['status']:
185 compute_resource = vnfc['computeresource']
186 vminst = VmInstModel.objects.filter(resouceid=compute_resource['resourceid']).first()
187 VNFCInstModel.objects.create(
188 vnfcinstanceid=vnfc['vnfcinstanceid'],
190 vdutype=vnfc['vdutype'],
191 nfinstid=self.nf_inst_id,
194 if 'failed' == vl['status']:
196 network_resource = vl['networkresource']
197 subnet_resource = vl['subnetworkresource']
198 networkinst = NetworkInstModel.objects.filter(resouceid=network_resource['resourceid']).first()
199 subnetinst = SubNetworkInstModel.objects.filter(resouceid=subnet_resource['resourceid']).first()
200 VLInstModel.objects.create(
201 vlinstanceid=vl['virtuallinkinstanceid'],
202 vldid=vl['virtuallinkdescid'],
204 ownerid=self.nf_inst_id,
205 relatednetworkid=networkinst.networkid,
206 relatedsubnetworkid=subnetinst.subnetworkid)
209 if 'failed' == cp['status']:
211 port_resource = cp['portresource']
212 portinst = PortInstModel.objects.filter(resouceid=port_resource['resourceid']).first()
213 ttt = portinst.portid
214 CPInstModel.objects.create(
215 cpinstanceid=cp['cpinstanceid'],
218 relatedport=portinst.portid,
219 ownertype=cp['ownertype'],
220 ownerid=cp['ownerid'],
221 vlinstanceid=cp['virtuallinkinstanceid'])
222 # self.add_job(43, 'INST_DPLY_VM_PRGS')
223 logger.info("[NF instantiation] confirm all vms are active end")
225 def wait_inst_finish(self, args):
227 logger.info('wait_inst_finish, args=%s' % args)
228 # WaitInstFinishTask(args).do_biz()
229 return {'result': '100', 'msg': 'Nf instancing wait finish', 'context': {}}
230 except Exception as e:
231 logger.error('Nf instancing wait exception=%s' % e.message)
232 logger.error(traceback.format_exc())
233 return {'result': '255', 'msg': 'Nf instancing wait exception', 'context': {}}
235 def lcm_notify(self, args):
237 logger.info('lcm_notify, args=%s' % args)
238 # LcmNotifyTask(args).do_biz()
239 return {'result': '100', 'msg': 'Nf instancing lcm notify finish', 'context': {}}
240 except Exception as e:
241 logger.error('Nf instancing lcm notify exception=%s' % e.message)
242 logger.error(traceback.format_exc())
243 return {'result': '255', 'msg': 'Nf instancing lcm notify exception', 'context': {}}
245 def rollback(self, args):
247 logger.info('inst_exception, args=%s' % args)
248 # InstExceptionTask(args).do_biz()
249 return {'result': '100', 'msg': 'Nf instancing exception process finish', 'context': {}}
250 except Exception as e:
251 logger.error('Nf instancing exception process exception=%s' % e.message)
252 logger.error(traceback.format_exc())
253 return {'result': '255', 'msg': 'Nf instancing exception process exception', 'context': {}}
255 def load_nfvo_config(self):
256 logger.info("[NF instantiation]get nfvo connection info start")
257 reg_info = NfvoRegInfoModel.objects.filter(vnfminstid='vnfm111').first()
259 self.nfvo_inst_id = reg_info.nfvoid
260 logger.info("[NF instantiation] Registered nfvo id is [%s]"%self.nfvo_inst_id)
262 raise NFLCMException("Nfvo was not registered")
263 logger.info("[NF instantiation]get nfvo connection info end")
265 def vnf_inst_failed_handle(self, error_msg):
266 logger.error('VNF instantiation failed, detail message: %s' % error_msg)
267 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
268 JobUtil.add_job_status(self.job_id, 255, error_msg)
269 # JobUtil.add_job_status(self.job_id, 255, 'VNF instantiation failed, detail message: %s' % error_msg, 0)
271 def add_job_and_update_table(self, progress, msgid, args_=None):
272 logger.info('add job, progress=%s, msgid=%s, args=%s' % (progress, msgid, args_))
273 JobUtil.add_job_status(self.job_id, 90, '')