Modify code of apply_grant
[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, NfvoRegInfoModel, VmInstModel, NetworkInstModel, \
20     SubNetworkInstModel, PortInstModel, StorageInstModel, FlavourInstModel, VNFCInstModel, VLInstModel, CPInstModel
21 from lcm.pub.exceptions import NFLCMException
22 from lcm.pub.msapi.catalog import query_rawdata_from_catalog
23 from lcm.pub.msapi.nfvolcm import vnfd_rawdata_get, apply_grant_to_nfvo, notify_lcm_to_nfvo, get_packageinfo_by_vnfdid
24 from lcm.pub.utils import toscautil
25 from lcm.pub.utils.jobutil import JobUtil
26 from lcm.pub.utils.timeutil import now_time
27 from lcm.pub.utils.values import ignore_case_get
28 from lcm.pub.vimapi import adaptor
29
30 logger = logging.getLogger(__name__)
31
32
33 class InstVnf(Thread):
34     def __init__(self, data, nf_inst_id, job_id):
35         super(InstVnf, self).__init__()
36         self.data = data
37         self.nf_inst_id = nf_inst_id
38         self.job_id = job_id
39         self.nfvo_inst_id = ''
40         self.vnfm_inst_id = ''
41         self.csar_id = ''
42         self.vnfd_info = []
43         self.inst_resource = {'volumn': [],  # [{"vim_id": ignore_case_get(ret, "vim_id")},{}]
44                               'network': [],
45                               'subnet': [],
46                               'port': [],
47                               'flavor': [],
48                               'vm': [],
49                               }
50         # self.create_res_result = {
51         #     'jobid': 'res_001',
52         #     'resourceResult': [{'name': 'vm01'}, {'name': 'vm02'}],
53         #     'resource_result':{
54         #         'affectedvnfc':[
55         #             {
56         #                 'status':'success',
57         #                 'vnfcinstanceid':'1',
58         #                 'computeresource':{'resourceid':'11'},
59         #                 'vduid':'111',
60         #                 'vdutype':'1111'
61         #             }
62         #         ],
63         #         'affectedvirtuallink':[
64         #             {
65         #                 'status': 'success',
66         #                 'virtuallinkinstanceid':'',
67         #                 'networkresource':{'resourceid':'1'},
68         #                 'subnetworkresource':{'resourceid':'1'},
69         #                 'virtuallinkdescid': '',
70         #             }
71         #         ],
72         #         'affectedcp':[{
73         #             'status': 'success',
74         #             'portresource':{'resourceid':'1'},
75         #             'cpinstanceid':'2',
76         #             'cpdid':'22',
77         #             'ownertype':'222',
78         #             'ownerid':'2222',
79         #             'virtuallinkinstanceid':'22222',
80         #
81         #         }],
82         #
83         #     }
84         # }
85
86     def run(self):
87         try:
88             self.inst_pre()
89             self.apply_grant()
90             self.create_res()
91             self.lcm_notify()
92             JobUtil.add_job_status(self.job_id, 100, "Instantiate Vnf success.")
93             # is_exist = JobStatusModel.objects.filter(jobid=self.job_id).exists()
94             # logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
95         except NFLCMException as e:
96             self.vnf_inst_failed_handle(e.message)
97             # self.rollback(e.message)
98         except:
99             self.vnf_inst_failed_handle('unexpected exception')
100             logger.error(traceback.format_exc())
101             # self.rollback('unexpected exception')
102
103     def inst_pre(self):
104         vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
105         if not vnf_insts.exists():
106             raise NFLCMException('VNF nf_inst_id is not exist.')
107
108         # self.vnfm_inst_id = vnf_insts[0].vnfm_inst_id
109         if vnf_insts[0].status != 'NOT_INSTANTIATED':
110             raise NFLCMException('VNF instantiationState is not NOT_INSTANTIATED.')
111
112         JobUtil.add_job_status(self.job_id, 5, 'Get packageinfo by vnfd_id')
113         # get csar_id from nslcm by vnfd_id
114         self.package_info = get_packageinfo_by_vnfdid(vnf_insts[0].vnfdid)
115         self.package_id = ignore_case_get(self.package_info, "package_id")
116         self.csar_id = ignore_case_get(self.package_info, "csar_id")
117
118         JobUtil.add_job_status(self.job_id, 10, 'Get rawdata from catalog by csar_id')
119         #get rawdata from catalog by csar_id
120         input_parameters = []
121         for key, val in self.data['additionalParams'].items():
122             input_parameters.append({"key": key, "value": val})
123         raw_data = query_rawdata_from_catalog(self.csar_id, input_parameters)
124         self.vnfd_info = toscautil.convert_vnfd_model(raw_data["rawData"])  # convert to inner json
125         self.vnfd_info = json.JSONDecoder().decode(self.vnfd_info)
126
127         self.checkParameterExist()
128         # update NfInstModel
129         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).\
130             update(flavour_id=ignore_case_get(self.data, "flavourId"),
131                    input_params=self.data,
132                    vnfd_model=self.vnfd_info,
133                    localizationLanguage=ignore_case_get(self.data, 'localizationLanguage'),
134                    lastuptime=now_time())
135         JobUtil.add_job_status(self.job_id, 15, 'Nf instancing pre-check finish')
136         logger.info("Nf instancing pre-check finish")
137
138     def apply_grant(self):
139         logger.info('[NF instantiation] send resource grand request to nfvo start')
140         # self.check_vm_capacity()
141         content_args = {'vnfInstanceId': self.nf_inst_id, 'vnfDescriptorId': '',
142                         'lifecycleOperation': 'Instantiate', 'jobId': self.job_id,
143                         'addResource': [], 'removeResource': [],
144                         'placementConstraint': [], 'additionalParam': {}}
145
146         vdus = ignore_case_get(self.vnfd_info, "vdus")
147         res_index = 1
148         for vdu in vdus:
149             location_info = ignore_case_get(ignore_case_get(vdu, "properties"), "location_info")
150             res_def = {'type': 'VDU',
151                        'resDefId': str(res_index),
152                        'resDesId': ignore_case_get(vdu, "vdu_id"),
153                        'vimid': ignore_case_get(location_info, "vimId"),
154                        'tenant': ignore_case_get(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(status='INSTANTIATED', lastuptime=now_time())
165         JobUtil.add_job_status(self.job_id,20, 'Nf instancing apply grant finish')
166         logger.info("Nf instancing apply grant finish")
167
168     def create_res(self):
169         logger.info("[NF instantiation] create resource start")
170         adaptor.create_vim_res('', self.do_notify, self.do_rollback)
171
172         JobUtil.add_job_status(self.job_id, 70, '[NF instantiation] create resource finish')
173         logger.info("[NF instantiation] create resource finish")
174
175     # def check_res_status(self):
176     #     logger.info("[NF instantiation] confirm all vms are active start")
177     #     vnfcs = self.create_res_result['resource_result']['affectedvnfc']
178     #     for vnfc in vnfcs:
179     #         if 'success' != vnfc['status']:
180     #             logger.error("VNFC_STATUS_IS_NOT_ACTIVE[vduid=%s]" % vnfc['vduId'])
181     #             raise NFLCMException(msgid="VNFC_STATUS_IS_NOT_ACTIVE[vduid=%s]", args=vnfc['vduId'])
182     #
183     #     JobUtil.add_job_status(self.job_id, 80, 'SAVE_VNFC_TO_DB')
184     #     vls = self.create_res_result['resource_result']['affectedvirtuallink']
185     #     cps = self.create_res_result['resource_result']['affectedcp']
186     #
187     #     for vnfc in vnfcs:
188     #         if 'failed' == vnfc['status']:
189     #             continue
190     #         compute_resource = vnfc['computeresource']
191     #         vminst = VmInstModel.objects.filter(resouceid=compute_resource['resourceid']).first()
192     #         VNFCInstModel.objects.create(
193     #             vnfcinstanceid=vnfc['vnfcinstanceid'],
194     #             vduid=vnfc['vduid'],
195     #             vdutype=vnfc['vdutype'],
196     #             nfinstid=self.nf_inst_id,
197     #             vmid=vminst.vmid)
198     #     for vl in vls:
199     #         if 'failed' == vl['status']:
200     #             continue
201     #         network_resource = vl['networkresource']
202     #         subnet_resource = vl['subnetworkresource']
203     #         networkinst = NetworkInstModel.objects.filter(resouceid=network_resource['resourceid']).first()
204     #         subnetinst = SubNetworkInstModel.objects.filter(resouceid=subnet_resource['resourceid']).first()
205     #         VLInstModel.objects.create(
206     #             vlinstanceid=vl['virtuallinkinstanceid'],
207     #             vldid=vl['virtuallinkdescid'],
208     #             ownertype='0',
209     #             ownerid=self.nf_inst_id,
210     #             relatednetworkid=networkinst.networkid,
211     #             relatedsubnetworkid=subnetinst.subnetworkid)
212     #     # # for vs in vss:
213     #     for cp in cps:
214     #         if 'failed' == cp['status']:
215     #             continue
216     #         port_resource = cp['portresource']
217     #         portinst = PortInstModel.objects.filter(resouceid=port_resource['resourceid']).first()
218     #         ttt = portinst.portid
219     #         CPInstModel.objects.create(
220     #             cpinstanceid=cp['cpinstanceid'],
221     #             cpdid=cp['cpdid'],
222     #             relatedtype='2',
223     #             relatedport=portinst.portid,
224     #             ownertype=cp['ownertype'],
225     #             ownerid=cp['ownerid'],
226     #             vlinstanceid=cp['virtuallinkinstanceid'])
227     #     # self.add_job(43, 'INST_DPLY_VM_PRGS')
228     #     logger.info("[NF instantiation] confirm all vms are active end")
229
230     def lcm_notify(self):
231         logger.info('[NF instantiation] send notify request to nfvo start')
232         reg_info = NfvoRegInfoModel.objects.filter(vnfminstid=self.vnfm_inst_id).first()
233         # vm_info = VmInstModel.objects.filter(nfinstid=self.nf_inst_id)
234         vmlist = []
235         # nfs = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
236         # nf = nfs[0]
237         # allocate_data = json.loads(nf.initallocatedata)
238         # vmlist = json.loads(nf.predefinedvm)
239         addition_param = {'vmList': vmlist}
240         affected_vnfc = []
241         vnfcs = VNFCInstModel.objects.filter(nfinstid=self.nf_inst_id)
242         for vnfc in vnfcs:
243             compute_resource = {}
244             if vnfc.vmid:
245                 vm = VmInstModel.objects.filter(vmid=vnfc.vmid)
246                 if vm:
247                     compute_resource = {'vimId': vm[0].vimid, 'resourceId': vm[0].resouceid,
248                                         'resourceName': vm[0].vmname, 'tenant': vm[0].tenant}
249             affected_vnfc.append(
250                 {'vnfcInstanceId': vnfc.vnfcinstanceid, 'vduId': vnfc.vduid, 'changeType': 'added',
251                  'computeResource': compute_resource, 'storageResource': [], 'vduType': vnfc.vdutype})
252         affected_vl = []
253         vls = VLInstModel.objects.filter(ownerid=self.nf_inst_id)
254         for vl in vls:
255             network_resource = {}
256             subnet_resource = {}
257             if vl.relatednetworkid:
258                 network = NetworkInstModel.objects.filter(networkid=vl.relatednetworkid)
259                 subnet = SubNetworkInstModel.objects.filter(subnetworkid=vl.relatedsubnetworkid)
260                 if network:
261                     network_resource = {'vimId': network[0].vimid, 'resourceId': network[0].resouceid,
262                                         'resourceName': network[0].name, 'tenant': network[0].tenant}
263                 if subnet:
264                     subnet_resource = {'vimId': subnet[0].vimid, 'resourceId': subnet[0].resouceid,
265                                        'resourceName': subnet[0].name, 'tenant': subnet[0].tenant}
266             affected_vl.append(
267                 {'virtualLinkInstanceId': vl.vlinstanceid, 'virtualLinkDescId': vl.vldid, 'changeType': 'added',
268                  'networkResource': network_resource, 'subnetworkResource': subnet_resource, 'tenant': vl.tenant})
269         affected_vs = []
270         vss = StorageInstModel.objects.filter(instid=self.nf_inst_id)
271         for vs in vss:
272             affected_vs.append(
273                 {'virtualStorageInstanceId': vs.storageid, 'virtualStorageDescId': '', 'changeType': 'added',
274                  'storageResource': {'vimId': vs.vimid, 'resourceId': vs.resouceid,
275                                      'resourceName': vs.name, 'tenant': vs.tenant}})
276         affected_cp = []
277         # vnfc cps
278         for vnfc in vnfcs:
279             cps = CPInstModel.objects.filter(ownerid=vnfc.vnfcinstanceid, ownertype=3)
280             for cp in cps:
281                 port_resource = {}
282                 if cp.relatedport:
283                     port = PortInstModel.objects.filter(portid=cp.relatedport)
284                     if port:
285                         port_resource = {'vimId': port[0].vimid, 'resourceId': port[0].resouceid,
286                                          'resourceName': port[0].name, 'tenant': port[0].tenant}
287                 affected_cp.append(
288                     {'cPInstanceId': cp.cpinstanceid, 'cpdId': cp.cpdid, 'ownerid': cp.ownerid,
289                      'ownertype': cp.ownertype, 'changeType': 'added', 'portResource': port_resource,
290                      'virtualLinkInstanceId': cp.vlinstanceid})
291         # nf cps
292         cps = CPInstModel.objects.filter(ownerid=self.nf_inst_id, ownertype=0)
293         logger.info('vnf_inst_id=%s, cps size=%s' % (self.nf_inst_id, cps.count()))
294         for cp in cps:
295             port_resource = {}
296             if cp.relatedport:
297                 port = PortInstModel.objects.filter(portid=cp.relatedport)
298                 if port:
299                     port_resource = {'vimId': port[0].vimid, 'resourceId': port[0].resouceid,
300                                      'resourceName': port[0].name, 'tenant': port[0].tenant}
301             affected_cp.append(
302                 {'cPInstanceId': cp.cpinstanceid, 'cpdId': cp.cpdid, 'ownerid': cp.ownerid, 'ownertype': cp.ownertype,
303                  'changeType': 'added', 'portResource': port_resource,
304                  'virtualLinkInstanceId': cp.vlinstanceid})
305         # affectedcapacity = {}
306         # reserved_total = allocate_data.get('reserved_total', {})
307         # affectedcapacity['vm'] = str(reserved_total.get('vmnum', 0))
308         # affectedcapacity['vcpu'] = str(reserved_total.get('vcpunum', 0))
309         # affectedcapacity['vMemory'] = str(reserved_total.get('memorysize', 0))
310         # affectedcapacity['port'] = str(reserved_total.get('portnum', 0))
311         # affectedcapacity['localStorage'] = str(reserved_total.get('hdsize', 0))
312         # affectedcapacity['sharedStorage'] = str(reserved_total.get('shdsize', 0))
313         content_args = {
314             # "vnfdmodule": allocate_data,
315             "additionalParam": addition_param,
316             "nfvoInstanceId": reg_info.nfvoid,
317             "vnfmInstanceId": self.vnfm_inst_id,
318             "status": 'finished',
319             "nfInstanceId": self.nf_inst_id,
320             "operation": 'instantiate',
321             "jobId": '',
322             # 'affectedcapacity': affectedcapacity,
323             'affectedService': [],
324             'affectedVnfc': affected_vnfc,
325             'affectedVirtualLink': affected_vl,
326             'affectedVirtualStorage': affected_vs,
327             'affectedCp': affected_cp}
328         logger.info('content_args=%s' % content_args)
329         # call rest api
330         resp = notify_lcm_to_nfvo(content_args, self.nf_inst_id)
331         logger.info('[NF instantiation] get lcm response %s' % resp)
332         if resp[0] != 0:
333             logger.error("notify lifecycle to nfvo failed.[%s]" % resp[1])
334             raise NFLCMException("send notify request to nfvo failed")
335         logger.info('[NF instantiation] send notify request to nfvo end')
336
337     def load_nfvo_config(self):
338         logger.info("[NF instantiation]get nfvo connection info start")
339         reg_info = NfvoRegInfoModel.objects.filter(vnfminstid='vnfm111').first()
340         if reg_info:
341             self.vnfm_inst_id = reg_info.vnfminstid
342             self.nfvo_inst_id = reg_info.nfvoid
343             logger.info("[NF instantiation] Registered nfvo id is [%s]" % self.nfvo_inst_id)
344         else:
345             raise NFLCMException("Nfvo was not registered")
346         logger.info("[NF instantiation]get nfvo connection info end")
347
348     def vnf_inst_failed_handle(self, error_msg):
349         logger.error('VNF instantiation failed, detail message: %s' % error_msg)
350         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
351         JobUtil.add_job_status(self.job_id, 255, error_msg)
352
353     def do_notify(self, res_type, progress, ret):
354         logger.info('creating [%s] resource' % res_type)
355         progress = 20 + int(progress/2)     # 20-70
356         if res_type == adaptor.OPT_CREATE_VOLUME:
357             logger.info('Create vloumns!')
358             if ret["returnCode"] == adaptor.RES_NEW:  # new create
359                 self.inst_resource['volumn'].append({"vim_id": ignore_case_get(ret, "vim_id"),
360                                                      "res_id": ignore_case_get(ret, "res_id")})
361             JobUtil.add_job_status(self.job_id, progress, 'Create vloumns!')
362             StorageInstModel.objects.create(
363                 storageid='1',
364                 vimid='1',
365                 resouceid='1',
366                 name='40G',
367                 tenant='admin',
368                 insttype=0,
369                 is_predefined=ret["returnCode"],
370                 instid=self.nf_inst_id)
371         elif res_type == adaptor.OPT_CREATE_NETWORK:
372             logger.info('Create networks!')
373             if ret["returnCode"] == adaptor.RES_NEW:
374                 self.inst_resource['network'].append({"vim_id": ignore_case_get(ret, "vim_id"),
375                                                       "res_id": ignore_case_get(ret, "res_id")})
376             # self.inst_resource['network'].append({"vim_id": "1"}, {"res_id": "2"})
377             JobUtil.add_job_status(self.job_id, progress, 'Create networks!')
378             NetworkInstModel.objects.create(
379                 networkid='1',
380                 vimid='1',
381                 resouceid='1',
382                 name='pnet_network',
383                 tenant='admin',
384                 insttype=0,
385                 is_predefined=ret["returnCode"],
386                 instid=self.nf_inst_id)
387         elif res_type == adaptor.OPT_CREATE_SUBNET:
388             logger.info('Create subnets!')
389             if ret["returnCode"] == adaptor.RES_NEW:
390                 self.inst_resource['subnet'].append({"vim_id": ignore_case_get(ret, "vim_id"),
391                                                      "res_id": ignore_case_get(ret, "res_id")})
392             # self.inst_resource['subnet'].append({"vim_id": "1"}, {"res_id": "2"})
393             JobUtil.add_job_status(self.job_id, progress, 'Create subnets!')
394             SubNetworkInstModel.objects.create(
395                 subnetworkid='1',
396                 vimid='1',
397                 resouceid='1',
398                 networkid='1',
399                 name='sub_pnet',
400                 tenant='admin',
401                 insttype=0,
402                 is_predefined=ret["returnCode"],
403                 instid=self.nf_inst_id)
404         elif res_type == adaptor.OPT_CREATE_PORT:
405             logger.info('Create ports!')
406             if ret["returnCode"] == adaptor.RES_NEW:
407                 self.inst_resource['port'].append({"vim_id": ignore_case_get(ret, "vim_id"),
408                                                    "res_id": ignore_case_get(ret, "res_id")})
409             # self.inst_resource['port'].append({"vim_id": "1"}, {"res_id": "2"})
410             JobUtil.add_job_status(self.job_id, progress, 'Create ports!')
411             PortInstModel.objects.create(
412                 portid='1',
413                 networkid='1',
414                 subnetworkid='1',
415                 vimid='1',
416                 resouceid='1',
417                 name='aaa_pnet_cp',
418                 tenant='admin',
419                 insttype=0,
420                 is_predefined=ret["returnCode"],
421                 instid=self.nf_inst_id)
422         elif res_type == adaptor.OPT_CREATE_FLAVOR:
423             logger.info('Create flavors!')
424             if ret["returnCode"] == adaptor.RES_NEW:
425                 self.inst_resource['flavor'].append({"vim_id": ignore_case_get(ret, "vim_id"),
426                                                      "res_id": ignore_case_get(ret, "res_id")})
427             # self.inst_resource['flavor'].append({"vim_id": "1"}, {"res_id": "2"})
428             JobUtil.add_job_status(self.job_id, progress, 'Create flavors!')
429             FlavourInstModel.objects.create(
430                 falavourid='1',
431                 name='1',
432                 vcpu='1',
433                 extraspecs='1',
434                 is_predefined=ret["returnCode"],
435                 instid=self.nf_inst_id)
436         elif res_type == adaptor.OPT_CREATE_VM:
437             logger.info('Create vms!')
438             if ret["returnCode"] == adaptor.RES_NEW:
439                 self.inst_resource['vm'].append({"vim_id": ignore_case_get(ret, "vim_id"),
440                                                  "res_id": ignore_case_get(ret, "res_id")})
441             # self.inst_resource['vm'].append({"vim_id": "1"}, {"res_id": "2"})
442             JobUtil.add_job_status(self.job_id, progress, 'Create vms!')
443             VmInstModel.objects.create(
444                 vmid="1",
445                 vimid="1",
446                 resouceid="11",
447                 insttype=0,
448                 instid=self.nf_inst_id,
449                 vmname="test_01",
450                 is_predefined=ret["returnCode"],
451                 operationalstate=1)
452
453     def do_rollback(self, args_=None):
454         logger.error('error info : %s' % args_)
455         adaptor.delete_vim_res(self.inst_resource, self.do_notify_delete)
456         logger.error('rollback resource complete')
457
458         StorageInstModel.objects.filter(instid=self.nf_inst_id).delete()
459         NetworkInstModel.objects.filter(instid=self.nf_inst_id).delete()
460         SubNetworkInstModel.objects.filter(instid=self.nf_inst_id).delete()
461         PortInstModel.objects.filter(instid=self.nf_inst_id).delete()
462         FlavourInstModel.objects.filter(instid=self.nf_inst_id).delete()
463         VmInstModel.objects.filter(instid=self.nf_inst_id).delete()
464         logger.error('delete table complete')
465         raise NFLCMException("Create resource failed")
466
467     def do_notify_delete(self, ret):
468         logger.error('Deleting [%s] resource' % ret)
469
470     def checkParameterExist(self):
471         # if ignore_case_get(self.data, "flavourId") not in self.vnfd_info:
472         #     raise NFLCMException('Input parameter is not defined in vnfd_info.')
473         pass