change lcm notify code and test case
[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, 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
27
28 logger = logging.getLogger(__name__)
29
30
31 class InstVnf(Thread):
32     def __init__(self, data, nf_inst_id, job_id):
33         super(InstVnf, self).__init__()
34         self.data = data
35         self.nf_inst_id = nf_inst_id
36         self.job_id = job_id
37         self.nfvo_inst_id = ''
38         self.vnfm_inst_id = ''
39         self.vnfd_info = []
40         self.inst_resource = {'volumn': [],  # [{"vim_id": ignore_case_get(ret, "vim_id")},{}]11
41                               'network': [],
42                               'subnet': [],
43                               'port': [],
44                               'flavor': [],
45                               'vm': [],
46                               }
47         # self.create_res_result = {
48         #     'jobid': 'res_001',
49         #     'resourceResult': [{'name': 'vm01'}, {'name': 'vm02'}],
50         #     'resource_result':{
51         #         'affectedvnfc':[
52         #             {
53         #                 'status':'success',
54         #                 'vnfcinstanceid':'1',
55         #                 'computeresource':{'resourceid':'11'},
56         #                 'vduid':'111',
57         #                 'vdutype':'1111'
58         #             }
59         #         ],
60         #         'affectedvirtuallink':[
61         #             {
62         #                 'status': 'success',
63         #                 'virtuallinkinstanceid':'',
64         #                 'networkresource':{'resourceid':'1'},
65         #                 'subnetworkresource':{'resourceid':'1'},
66         #                 'virtuallinkdescid': '',
67         #             }
68         #         ],
69         #         'affectedcp':[{
70         #             'status': 'success',
71         #             'portresource':{'resourceid':'1'},
72         #             'cpinstanceid':'2',
73         #             'cpdid':'22',
74         #             'ownertype':'222',
75         #             'ownerid':'2222',
76         #             'virtuallinkinstanceid':'22222',
77         #
78         #         }],
79         #
80         #     }
81         # }
82
83     def run(self):
84         try:
85             self.inst_pre()
86             self.apply_grant()
87             self.create_res()
88             # self.check_res_status()
89             # self.wait_inst_finish(args)
90             self.lcm_notify()
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)
97         except:
98             self.vnf_inst_failed_handle('unexpected exception')
99             logger.error(traceback.format_exc())
100             # self.rollback('unexpected exception')
101
102     def inst_pre(self):
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.')
106
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.')
110
111         # get rawdata by vnfd_id
112         ret = vnfd_rawdata_get(vnf_insts[0].vnfdid)
113         if ret[0] != 0:
114             raise NFLCMException("Get vnfd_raw_data failed.")
115         self.vnfd_info = json.JSONDecoder().decode(ret[1])
116         # checkParameterExist
117         for cp in self.data:
118             if cp not in self.vnfd_info:
119                 raise NFLCMException('Input parameter is not defined in vnfd_info.')
120         # get nfvo info
121         JobUtil.add_job_status(self.job_id, 5, 'Get nfvo connection info')
122         self.load_nfvo_config()
123
124         # update NfInstModel
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")
135
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': {}}
143
144         vdus = ignore_case_get(self.vnfd_info, "vdus")
145         res_index = 1
146         for vdu in vdus:
147             res_def = {'type': 'VDU',
148                        'resourceDefinitionId': str(res_index),
149                        'vduId': ignore_case_get(vdu, "vdu_id"),
150                        'vimid': '',
151                        'tenant': ''}
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)
156             res_index += 1
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)
160         if resp[0] != 0:
161             raise NFLCMException('Nf instancing apply grant exception')
162
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")
168
169     def create_res(self):
170         logger.info("[NF instantiation] create resource start")
171         adaptor.create_vim_res('', self.do_notify, self.do_rollback)
172
173         JobUtil.add_job_status(self.job_id, 70, '[NF instantiation] create resource finish')
174         logger.info("[NF instantiation] create resource finish")
175
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']
179     #     for vnfc in vnfcs:
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'])
183     #
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']
187     #
188     #     for vnfc in vnfcs:
189     #         if 'failed' == vnfc['status']:
190     #             continue
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,
198     #             vmid=vminst.vmid)
199     #     for vl in vls:
200     #         if 'failed' == vl['status']:
201     #             continue
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'],
209     #             ownertype='0',
210     #             ownerid=self.nf_inst_id,
211     #             relatednetworkid=networkinst.networkid,
212     #             relatedsubnetworkid=subnetinst.subnetworkid)
213     #     # # for vs in vss:
214     #     for cp in cps:
215     #         if 'failed' == cp['status']:
216     #             continue
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'],
222     #             cpdid=cp['cpdid'],
223     #             relatedtype='2',
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")
230
231     # def wait_inst_finish(self, args):
232     #     try:
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': {}}
240
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)
245         vmlist = []
246         # nfs = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
247         # nf = nfs[0]
248         # allocate_data = json.loads(nf.initallocatedata)
249         # vmlist = json.loads(nf.predefinedvm)
250         addition_param = {'vmList': vmlist}
251         affected_vnfc = []
252         vnfcs = VNFCInstModel.objects.filter(nfinstid=self.nf_inst_id)
253         for vnfc in vnfcs:
254             compute_resource = {}
255             if vnfc.vmid:
256                 vm = VmInstModel.objects.filter(vmid=vnfc.vmid)
257                 if vm:
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})
263         affected_vl = []
264         vls = VLInstModel.objects.filter(ownerid=self.nf_inst_id)
265         for vl in vls:
266             network_resource = {}
267             subnet_resource = {}
268             if vl.relatednetworkid:
269                 network = NetworkInstModel.objects.filter(networkid=vl.relatednetworkid)
270                 subnet = SubNetworkInstModel.objects.filter(subnetworkid=vl.relatedsubnetworkid)
271                 if network:
272                     network_resource = {'vimId': network[0].vimid, 'resourceId': network[0].resouceid,
273                                         'resourceName': network[0].name, 'tenant': network[0].tenant}
274                 if subnet:
275                     subnet_resource = {'vimId': subnet[0].vimid, 'resourceId': subnet[0].resouceid,
276                                        'resourceName': subnet[0].name, 'tenant': subnet[0].tenant}
277             affected_vl.append(
278                 {'virtualLinkInstanceId': vl.vlinstanceid, 'virtualLinkDescId': vl.vldid, 'changeType': 'added',
279                  'networkResource': network_resource, 'subnetworkResource': subnet_resource, 'tenant': vl.tenant})
280         affected_vs = []
281         vss = StorageInstModel.objects.filter(instid=self.nf_inst_id)
282         for vs in vss:
283             affected_vs.append(
284                 {'virtualStorageInstanceId': vs.storageid, 'virtualStorageDescId': '', 'changeType': 'added',
285                  'storageResource': {'vimId': vs.vimid, 'resourceId': vs.resouceid,
286                                      'resourceName': vs.name, 'tenant': vs.tenant}})
287         affected_cp = []
288         # vnfc cps
289         for vnfc in vnfcs:
290             cps = CPInstModel.objects.filter(ownerid=vnfc.vnfcinstanceid, ownertype=3)
291             for cp in cps:
292                 port_resource = {}
293                 if cp.relatedport:
294                     port = PortInstModel.objects.filter(portid=cp.relatedport)
295                     if port:
296                         port_resource = {'vimId': port[0].vimid, 'resourceId': port[0].resouceid,
297                                          'resourceName': port[0].name, 'tenant': port[0].tenant}
298                 affected_cp.append(
299                     {'cPInstanceId': cp.cpinstanceid, 'cpdId': cp.cpdid, 'ownerid': cp.ownerid,
300                      'ownertype': cp.ownertype, 'changeType': 'added', 'portResource': port_resource,
301                      'virtualLinkInstanceId': cp.vlinstanceid})
302         # nf cps
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()))
305         for cp in cps:
306             port_resource = {}
307             if cp.relatedport:
308                 port = PortInstModel.objects.filter(portid=cp.relatedport)
309                 if port:
310                     port_resource = {'vimId': port[0].vimid, 'resourceId': port[0].resouceid,
311                                      'resourceName': port[0].name, 'tenant': port[0].tenant}
312             affected_cp.append(
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))
324         content_args = {
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',
332             "jobId": '',
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)
340         # call rest api
341         resp = notify_lcm_to_nfvo(content_args, self.nf_inst_id)
342         logger.info('[NF instantiation] get lcm response %s' % resp)
343         if resp[0] != 0:
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')
347
348     # def rollback(self, args):
349     #     try:
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': {}}
357
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()
361         if reg_info:
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)
365         else:
366             raise NFLCMException("Nfvo was not registered")
367         logger.info("[NF instantiation]get nfvo connection info end")
368
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)
373
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(
384                 storageid='1',
385                 vimid='1',
386                 resouceid='1',
387                 name='40G',
388                 tenant='admin',
389                 insttype=0,
390                 instid=self.nf_inst_id)
391         elif res_type == adaptor.OPT_CREATE_NETWORK:
392             logger.info('Create networks!')
393             if ret["returnCode"] == adaptor.RES_NEW:
394                 self.inst_resource['network'].append({"vim_id": ignore_case_get(ret, "vim_id"),
395                                                       "res_id": ignore_case_get(ret, "res_id")})
396             # self.inst_resource['network'].append({"vim_id": "1"}, {"res_id": "2"})
397             JobUtil.add_job_status(self.job_id, progress, 'Create networks!')
398             NetworkInstModel.objects.create(
399                 networkid='1',
400                 vimid='1',
401                 resouceid='1',
402                 name='pnet_network',
403                 tenant='admin',
404                 insttype=0,
405                 instid=self.nf_inst_id)
406         elif res_type == adaptor.OPT_CREATE_SUBNET:
407             logger.info('Create subnets!')
408             if ret["returnCode"] == adaptor.RES_NEW:
409                 self.inst_resource['subnet'].append({"vim_id": ignore_case_get(ret, "vim_id"),
410                                                      "res_id": ignore_case_get(ret, "res_id")})
411             # self.inst_resource['subnet'].append({"vim_id": "1"}, {"res_id": "2"})
412             JobUtil.add_job_status(self.job_id, progress, 'Create subnets!')
413             SubNetworkInstModel.objects.create(
414                 subnetworkid='1',
415                 vimid='1',
416                 resouceid='1',
417                 networkid='1',
418                 name='sub_pnet',
419                 tenant='admin',
420                 insttype=0,
421                 instid=self.nf_inst_id)
422         elif res_type == adaptor.OPT_CREATE_PORT:
423             logger.info('Create ports!')
424             if ret["returnCode"] == adaptor.RES_NEW:
425                 self.inst_resource['port'].append({"vim_id": ignore_case_get(ret, "vim_id"),
426                                                    "res_id": ignore_case_get(ret, "res_id")})
427             # self.inst_resource['port'].append({"vim_id": "1"}, {"res_id": "2"})
428             JobUtil.add_job_status(self.job_id, progress, 'Create ports!')
429             PortInstModel.objects.create(
430                 portid='1',
431                 networkid='1',
432                 subnetworkid='1',
433                 vimid='1',
434                 resouceid='1',
435                 name='aaa_pnet_cp',
436                 tenant='admin',
437                 insttype=0,
438                 instid=self.nf_inst_id)
439         elif res_type == adaptor.OPT_CREATE_FLAVOR:
440             logger.info('Create flavors!')
441             if ret["returnCode"] == adaptor.RES_NEW:
442                 self.inst_resource['flavor'].append({"vim_id": ignore_case_get(ret, "vim_id"),
443                                                      "res_id": ignore_case_get(ret, "res_id")})
444             # self.inst_resource['flavor'].append({"vim_id": "1"}, {"res_id": "2"})
445             JobUtil.add_job_status(self.job_id, progress, 'Create flavors!')
446             FlavourInstModel.objects.create(
447                 falavourid='1',
448                 name='1',
449                 vcpu='1',
450                 extraspecs='1',
451                 instid=self.nf_inst_id)
452         elif res_type == adaptor.OPT_CREATE_VM:
453             logger.info('Create vms!')
454             if ret["returnCode"] == adaptor.RES_NEW:
455                 self.inst_resource['vm'].append({"vim_id": ignore_case_get(ret, "vim_id"),
456                                                  "res_id": ignore_case_get(ret, "res_id")})
457             # self.inst_resource['vm'].append({"vim_id": "1"}, {"res_id": "2"})
458             JobUtil.add_job_status(self.job_id, progress, 'Create vms!')
459             VmInstModel.objects.create(
460                 vmid="1",
461                 vimid="1",
462                 resouceid="11",
463                 insttype=0,
464                 instid=self.nf_inst_id,
465                 vmname="test_01",
466                 operationalstate=1)
467
468     def do_rollback(self, args_=None):
469         logger.error('error info : %s' % args_)
470         adaptor.delete_vim_res(self.inst_resource, self.do_notify_delete)
471         logger.error('rollback resource complete')
472
473         StorageInstModel.objects.filter(instid=self.nf_inst_id).delete()
474         NetworkInstModel.objects.filter(instid=self.nf_inst_id).delete()
475         SubNetworkInstModel.objects.filter(instid=self.nf_inst_id).delete()
476         PortInstModel.objects.filter(instid=self.nf_inst_id).delete()
477         FlavourInstModel.objects.filter(instid=self.nf_inst_id).delete()
478         VmInstModel.objects.filter(instid=self.nf_inst_id).delete()
479         logger.error('delete table complete')
480         raise NFLCMException("Create resource failed")
481
482     def do_notify_delete(self, ret):
483         logger.error('Deleting [%s] resource' % ret)