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 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
26 logger = logging.getLogger(__name__)
29 class InstVnf(Thread):
30 def __init__(self, data, nf_inst_id, job_id):
31 super(InstVnf, self).__init__()
33 self.nf_inst_id = nf_inst_id
35 self.nfvo_inst_id = ''
36 self.vnfm_inst_id = ''
37 self.create_res_result = {
39 'resourceResult': [{'name': 'vm01'}, {'name': 'vm02'}],
45 'computeresource':{'resourceid':'11'},
51 'vnfcinstanceid': '2',
52 'computeresource': {'resourceid':'22'},
57 'affectedvirtuallink':{
72 self.check_res_status()
73 # self.wait_inst_finish(args)
74 # self.lcm_notify(args)
75 JobUtil.add_job_status(self.job_id, 100, "Instantiate Vnf success.")
76 is_exist = JobStatusModel.objects.filter(jobid=self.job_id).exists()
77 logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
78 except NFLCMException as e:
79 self.vnf_inst_failed_handle(e.message)
80 # self.rollback(e.message)
82 # self.vnf_inst_failed_handle('unexpected exception')
83 logger.error(traceback.format_exc())
84 # self.rollback('unexpected exception')
87 vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
88 if not vnf_insts.exists():
89 raise NFLCMException('VNF nf_inst_id is not exist.')
91 self.vnfm_inst_id = vnf_insts[0].vnfm_inst_id
92 if vnf_insts[0].instantiationState != 'NOT_INSTANTIATED':
93 raise NFLCMException('VNF instantiationState is not NOT_INSTANTIATED.')
95 #get rawdata by vnfd_id
96 ret = vnfd_rawdata_get(vnf_insts[0].vnfdid)
98 raise NFLCMException("Get vnfd_raw_data failed.")
99 self.vnfd_info = json.JSONDecoder().decode(ret[1])
102 if cp not in self.vnfd_info:
103 raise NFLCMException('Input parameter is not defined in vnfd_info.')
105 JobUtil.add_job_status(self.job_id, 5, 'GET_NFVO_CONNECTION_INFO')
106 self.load_nfvo_config()
109 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(flavour_id=ignore_case_get(self.data, "flavourId"),
110 vnf_level=ignore_case_get(self.data, 'instantiationLevelId'),
111 input_params=ignore_case_get(self.data, 'additionalParams'),
112 extension=ignore_case_get(self.data, ''),
113 initallocatedata=self.vnfd_info,
114 localizationLanguage=ignore_case_get(self.data, 'localizationLanguage'),
115 lastuptime=now_time())
117 def apply_grant(self):
118 logger.info('[NF instantiation] send resource grand request to nfvo start')
119 #self.check_vm_capacity()
120 content_args = {'nfvoInstanceId': self.nfvo_inst_id, 'vnfmInstanceId': self.vnfm_inst_id,
121 'nfInstanceId': self.nf_inst_id, 'nfDescriptorId': '',
122 'lifecycleOperation': 'Instantiate', 'jobId': self.job_id, 'addResource': [],
123 'removeResource': [], 'placementConstraint': [], 'exVimIdList': [], 'additionalParam': {}}
125 vdus = self.vnfd_info['vdus']
128 res_def = {'type': 'VDU', 'resourceDefinitionId': str(res_index), 'vduId': vdu['vdu_id'],
129 'vimid': '', 'tenant': ''}
130 if self.vnfd_info['metadata']['cross_dc']:
131 res_def['vimid'] = vdu['properties']['location_info']['vimId']
132 res_def['tenant'] = vdu['properties']['location_info']['tenant']
133 content_args['addResource'].append(res_def)
135 logger.info('content_args=%s' % content_args)
136 resp = apply_grant_to_nfvo(content_args)
137 logger.info("[NF instantiation] get grant response = %s" % resp)
139 raise NFLCMException('Nf instancing apply grant exception')
141 #update_resources_table()
142 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(instantiationState='INSTANTIATED', lastuptime=now_time())
143 JobUtil.add_job_status(self.job_id, 15, 'Nf instancing apply grant finish')
144 logger.info("Nf instancing apply grant finish")
146 def create_res(self):
147 logger.info("[NF instantiation] create resource start")
148 volumns = ignore_case_get(self.data, "volumn_storages")
149 #create_volumns(volumns)
150 JobUtil.add_job_status(self.job_id, 35, 'Nf instancing create resource(volumn_storages) finish')
152 vls = ignore_case_get(self.data, "vls")
153 # create_networks(vls)
154 JobUtil.add_job_status(self.job_id, 55, 'Nf instancing create resource(networks) finish')
156 vdus = ignore_case_get(self.data, "vdus")
158 JobUtil.add_job_status(self.job_id, 75, 'Nf instancing create resource(vms) finish')
160 logger.info("[NF instantiation] create resource end")
162 def check_res_status(self):
163 logger.info("[NF instantiation] confirm all vms are active start")
164 vnfcs = self.create_res_result['resource_result']['affectedvnfc']
166 if 'success' != vnfc['status']:
167 logger.error("VNFC_STATUS_IS_NOT_ACTIVE[vduid=%s]" % vnfc['vduId'])
168 raise NFLCMException(msgid="VNFC_STATUS_IS_NOT_ACTIVE[vduid=%s]", args=vnfc['vduId'])
170 JobUtil.add_job_status(self.job_id, 80, 'SAVE_VNFC_TO_DB')
171 vls = self.create_res_result['resource_result']['affectedvirtuallink']
172 cps = self.create_res_result['resource_result']['affectedcp']
175 if 'failed' == vnfc['status']:
177 compute_resource = vnfc['computeresource']
178 vminst = VmInstModel.objects.filter(resouceid=compute_resource['resourceid']).first()
179 VNFCInstModel.objects.create(
180 vnfcinstanceid=vnfc['vnfcinstanceid'],
182 vdutype=vnfc['vdutype'],
183 nfinstid=self.nf_inst_id,
186 # if 'failed' == vl['status']:
188 # network_resource = vl['networkresource']
189 # subnet_resource = vl['subnetworkresource']
190 # networkinst = NetworkInstModel.objects.filter(resouceid=network_resource['resourceid']).first()
191 # subnetinst = SubNetworkInstModel.objects.filter(resouceid=subnet_resource['resourceid']).first()
192 # VLInstModel.objects.create(
193 # vlinstanceid=vl['virtuallinkinstanceid'],
194 # vldid=vl['virtuallinkdescid'],
195 # ownertype='0', # VNF
196 # ownerid=self.nf_inst_id,
197 # relatednetworkid=networkinst.networkid,
198 # relatedsubnetworkid=subnetinst.subnetworkid)
201 # if 'failed' == cp['status']:
203 # port_resource = cp['portresource']
204 # portinst = PortInstModel.objects.filter(resouceid=port_resource['resourceid']).first()
205 # CPInstModel.objects.create(
206 # cpinstanceid=cp['cpinstanceid'],
208 # relatedtype='2', # port
209 # relatedport=portinst.portid,
210 # ownertype=cp['ownertype'],
211 # ownerid=cp['ownerid'],
212 # vlinstanceid=cp['virtuallinkinstanceid'])
213 # self.add_job(43, 'INST_DPLY_VM_PRGS')
214 logger.info("[NF instantiation] confirm all vms are active end")
216 def wait_inst_finish(self, args):
218 logger.info('wait_inst_finish, args=%s' % args)
219 # WaitInstFinishTask(args).do_biz()
220 return {'result': '100', 'msg': 'Nf instancing wait finish', 'context': {}}
221 except Exception as e:
222 logger.error('Nf instancing wait exception=%s' % e.message)
223 logger.error(traceback.format_exc())
224 return {'result': '255', 'msg': 'Nf instancing wait exception', 'context': {}}
226 def lcm_notify(self, args):
228 logger.info('lcm_notify, args=%s' % args)
229 # LcmNotifyTask(args).do_biz()
230 return {'result': '100', 'msg': 'Nf instancing lcm notify finish', 'context': {}}
231 except Exception as e:
232 logger.error('Nf instancing lcm notify exception=%s' % e.message)
233 logger.error(traceback.format_exc())
234 return {'result': '255', 'msg': 'Nf instancing lcm notify exception', 'context': {}}
236 def rollback(self, args):
238 logger.info('inst_exception, args=%s' % args)
239 # InstExceptionTask(args).do_biz()
240 return {'result': '100', 'msg': 'Nf instancing exception process finish', 'context': {}}
241 except Exception as e:
242 logger.error('Nf instancing exception process exception=%s' % e.message)
243 logger.error(traceback.format_exc())
244 return {'result': '255', 'msg': 'Nf instancing exception process exception', 'context': {}}
246 def load_nfvo_config(self):
247 logger.info("[NF instantiation]get nfvo connection info start")
248 reg_info = NfvoRegInfoModel.objects.filter(vnfminstid='vnfm111').first()
250 self.nfvo_inst_id = reg_info.nfvoid
251 logger.info("[NF instantiation] Registered nfvo id is [%s]"%self.nfvo_inst_id)
253 raise NFLCMException("Nfvo was not registered")
254 logger.info("[NF instantiation]get nfvo connection info end")
256 def vnf_inst_failed_handle(self, error_msg):
257 logger.error('VNF instantiation failed, detail message: %s' % error_msg)
258 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
259 JobUtil.add_job_status(self.job_id, 255, error_msg)
260 # JobUtil.add_job_status(self.job_id, 255, 'VNF instantiation failed, detail message: %s' % error_msg, 0)