define create res rollback func
[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, VNFCInstModel, \
20     NetworkInstModel, SubNetworkInstModel, VLInstModel, PortInstModel, CPInstModel, StorageInstModel, FlavourInstModel
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
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.create_res_result = {
40             'jobid': 'res_001',
41             'resourceResult': [{'name': 'vm01'}, {'name': 'vm02'}],
42             'resource_result':{
43                 'affectedvnfc':[
44                     {
45                         'status':'success',
46                         'vnfcinstanceid':'1',
47                         'computeresource':{'resourceid':'11'},
48                         'vduid':'111',
49                         'vdutype':'1111'
50                     }
51                 ],
52                 'affectedvirtuallink':[
53                     {
54                         'status': 'success',
55                         'virtuallinkinstanceid':'',
56                         'networkresource':{'resourceid':'1'},
57                         'subnetworkresource':{'resourceid':'1'},
58                         'virtuallinkdescid': '',
59                     }
60                 ],
61                 'affectedcp':[{
62                     'status': 'success',
63                     'portresource':{'resourceid':'1'},
64                     'cpinstanceid':'2',
65                     'cpdid':'22',
66                     'ownertype':'222',
67                     'ownerid':'2222',
68                     'virtuallinkinstanceid':'22222',
69
70                 }],
71
72             }
73         }
74
75     def run(self):
76         try:
77             self.inst_pre()
78             self.apply_grant()
79             self.create_res()
80             self.check_res_status()
81             # self.wait_inst_finish(args)
82             # self.lcm_notify(args)
83             JobUtil.add_job_status(self.job_id, 100, "Instantiate Vnf success.")
84             is_exist = JobStatusModel.objects.filter(jobid=self.job_id).exists()
85             logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
86         except NFLCMException as e:
87             self.vnf_inst_failed_handle(e.message)
88             # self.rollback(e.message)
89         except:
90             # self.vnf_inst_failed_handle('unexpected exception')
91             logger.error(traceback.format_exc())
92             # self.rollback('unexpected exception')
93
94     def inst_pre(self):
95         vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
96         if not vnf_insts.exists():
97             raise NFLCMException('VNF nf_inst_id is not exist.')
98
99         self.vnfm_inst_id = vnf_insts[0].vnfm_inst_id
100         if vnf_insts[0].instantiationState != 'NOT_INSTANTIATED':
101             raise NFLCMException('VNF instantiationState is not NOT_INSTANTIATED.')
102
103         #get rawdata by vnfd_id
104         ret = vnfd_rawdata_get(vnf_insts[0].vnfdid)
105         if ret[0] != 0:
106             raise NFLCMException("Get vnfd_raw_data failed.")
107         self.vnfd_info = json.JSONDecoder().decode(ret[1])
108         #checkParameterExist
109         for cp in self.data:
110             if cp not in self.vnfd_info:
111                 raise NFLCMException('Input parameter is not defined in vnfd_info.')
112         #get nfvo info
113         JobUtil.add_job_status(self.job_id, 5, 'GET_NFVO_CONNECTION_INFO')
114         self.load_nfvo_config()
115
116         #update NfInstModel
117         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(flavour_id=ignore_case_get(self.data, "flavourId"),
118                                                                     vnf_level=ignore_case_get(self.data, 'instantiationLevelId'),
119                                                                     input_params=ignore_case_get(self.data, 'additionalParams'),
120                                                                     extension=ignore_case_get(self.data, ''),
121                                                                     initallocatedata=self.vnfd_info,
122                                                                     localizationLanguage=ignore_case_get(self.data, 'localizationLanguage'),
123                                                                     lastuptime=now_time())
124
125     def apply_grant(self):
126         logger.info('[NF instantiation] send resource grand request to nfvo start')
127         #self.check_vm_capacity()
128         content_args = {'nfvoInstanceId': self.nfvo_inst_id, 'vnfmInstanceId': self.vnfm_inst_id,
129                         'nfInstanceId': self.nf_inst_id, 'nfDescriptorId': '',
130                         'lifecycleOperation': 'Instantiate', 'jobId': self.job_id, 'addResource': [],
131                         'removeResource': [], 'placementConstraint': [], 'exVimIdList': [], 'additionalParam': {}}
132
133         vdus = self.vnfd_info['vdus']
134         res_index = 1
135         for vdu in vdus:
136             res_def = {'type': 'VDU', 'resourceDefinitionId': str(res_index), 'vduId': vdu['vdu_id'],
137                        'vimid': '', 'tenant': ''}
138             if self.vnfd_info['metadata']['cross_dc']:
139                 res_def['vimid'] = vdu['properties']['location_info']['vimId']
140                 res_def['tenant'] = vdu['properties']['location_info']['tenant']
141             content_args['addResource'].append(res_def)
142             res_index += 1
143         logger.info('content_args=%s' % content_args)
144         resp = apply_grant_to_nfvo(content_args)
145         logger.info("[NF instantiation] get grant response = %s" % resp)
146         if resp[0] != 0:
147             raise NFLCMException('Nf instancing apply grant exception')
148
149         #update_resources_table()
150         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(instantiationState='INSTANTIATED', lastuptime=now_time())
151         JobUtil.add_job_status(self.job_id, 15, 'Nf instancing apply grant finish')
152         logger.info("Nf instancing apply grant finish")
153
154     def create_res(self):
155         logger.info("[NF instantiation] create resource start")
156         volumns = ignore_case_get(self.data, "volumn_storages")
157         #create_vim_res(data, do_notify, do_rollback)
158         #create_volumns(volumns)
159         JobUtil.add_job_status(self.job_id, 35, 'Nf instancing create resource(volumn_storages) finish')
160
161         vls = ignore_case_get(self.data, "vls")
162         # create_networks(vls)
163         JobUtil.add_job_status(self.job_id, 55, 'Nf instancing create resource(networks) finish')
164
165         vdus = ignore_case_get(self.data, "vdus")
166         # create_vdus(vdus)
167         JobUtil.add_job_status(self.job_id, 75, 'Nf instancing create resource(vms) finish')
168
169         logger.info("[NF instantiation] create resource end")
170
171     def check_res_status(self):
172         logger.info("[NF instantiation] confirm all vms are active start")
173         vnfcs = self.create_res_result['resource_result']['affectedvnfc']
174         for vnfc in vnfcs:
175             if 'success' != vnfc['status']:
176                 logger.error("VNFC_STATUS_IS_NOT_ACTIVE[vduid=%s]" % vnfc['vduId'])
177                 raise NFLCMException(msgid="VNFC_STATUS_IS_NOT_ACTIVE[vduid=%s]", args=vnfc['vduId'])
178
179         JobUtil.add_job_status(self.job_id, 80, 'SAVE_VNFC_TO_DB')
180         vls = self.create_res_result['resource_result']['affectedvirtuallink']
181         cps = self.create_res_result['resource_result']['affectedcp']
182
183         for vnfc in vnfcs:
184             if 'failed' == vnfc['status']:
185                 continue
186             compute_resource = vnfc['computeresource']
187             vminst = VmInstModel.objects.filter(resouceid=compute_resource['resourceid']).first()
188             VNFCInstModel.objects.create(
189                 vnfcinstanceid=vnfc['vnfcinstanceid'],
190                 vduid=vnfc['vduid'],
191                 vdutype=vnfc['vdutype'],
192                 nfinstid=self.nf_inst_id,
193                 vmid=vminst.vmid)
194         for vl in vls:
195             if 'failed' == vl['status']:
196                 continue
197             network_resource = vl['networkresource']
198             subnet_resource = vl['subnetworkresource']
199             networkinst = NetworkInstModel.objects.filter(resouceid=network_resource['resourceid']).first()
200             subnetinst = SubNetworkInstModel.objects.filter(resouceid=subnet_resource['resourceid']).first()
201             VLInstModel.objects.create(
202                 vlinstanceid=vl['virtuallinkinstanceid'],
203                 vldid=vl['virtuallinkdescid'],
204                 ownertype='0',
205                 ownerid=self.nf_inst_id,
206                 relatednetworkid=networkinst.networkid,
207                 relatedsubnetworkid=subnetinst.subnetworkid)
208         # # for vs in vss:
209         for cp in cps:
210             if 'failed' == cp['status']:
211                 continue
212             port_resource = cp['portresource']
213             portinst = PortInstModel.objects.filter(resouceid=port_resource['resourceid']).first()
214             ttt = portinst.portid
215             CPInstModel.objects.create(
216                 cpinstanceid=cp['cpinstanceid'],
217                 cpdid=cp['cpdid'],
218                 relatedtype='2',
219                 relatedport=portinst.portid,
220                 ownertype=cp['ownertype'],
221                 ownerid=cp['ownerid'],
222                 vlinstanceid=cp['virtuallinkinstanceid'])
223         # self.add_job(43, 'INST_DPLY_VM_PRGS')
224         logger.info("[NF instantiation] confirm all vms are active end")
225
226     def wait_inst_finish(self, args):
227         try:
228             logger.info('wait_inst_finish, args=%s' % args)
229             # WaitInstFinishTask(args).do_biz()
230             return {'result': '100', 'msg': 'Nf instancing wait finish', 'context': {}}
231         except Exception as e:
232             logger.error('Nf instancing wait exception=%s' % e.message)
233             logger.error(traceback.format_exc())
234             return {'result': '255', 'msg': 'Nf instancing wait exception', 'context': {}}
235
236     def lcm_notify(self, args):
237         try:
238             logger.info('lcm_notify, args=%s' % args)
239             # LcmNotifyTask(args).do_biz()
240             return {'result': '100', 'msg': 'Nf instancing lcm notify finish', 'context': {}}
241         except Exception as e:
242             logger.error('Nf instancing lcm notify exception=%s' % e.message)
243             logger.error(traceback.format_exc())
244             return {'result': '255', 'msg': 'Nf instancing lcm notify exception', 'context': {}}
245
246     def rollback(self, args):
247         try:
248             logger.info('inst_exception, args=%s' % args)
249             # InstExceptionTask(args).do_biz()
250             return {'result': '100', 'msg': 'Nf instancing exception process finish', 'context': {}}
251         except Exception as e:
252             logger.error('Nf instancing exception process exception=%s' % e.message)
253             logger.error(traceback.format_exc())
254             return {'result': '255', 'msg': 'Nf instancing exception process exception', 'context': {}}
255
256     def load_nfvo_config(self):
257         logger.info("[NF instantiation]get nfvo connection info start")
258         reg_info = NfvoRegInfoModel.objects.filter(vnfminstid='vnfm111').first()
259         if reg_info:
260             self.nfvo_inst_id = reg_info.nfvoid
261             logger.info("[NF instantiation] Registered nfvo id is [%s]"%self.nfvo_inst_id)
262         else:
263             raise NFLCMException("Nfvo was not registered")
264         logger.info("[NF instantiation]get nfvo connection info end")
265
266     def vnf_inst_failed_handle(self, error_msg):
267         logger.error('VNF instantiation failed, detail message: %s' % error_msg)
268         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
269         JobUtil.add_job_status(self.job_id, 255, error_msg)
270         # JobUtil.add_job_status(self.job_id, 255, 'VNF instantiation failed, detail message: %s' % error_msg, 0)
271
272     def do_rollback(self, progress, msgid, args_=None):
273         # logger.info('add job, progress=%s, msgid=%s, args=%s' % (progress, msgid, args_))
274
275         # adaptor.delete_vim_res(self.inst_resource, self.do_notify_delete)
276
277         StorageInstModel.objects.filter(instid=self.nf_inst_id).delete()
278         NetworkInstModel.objects.filter(instid=self.nf_inst_id).delete()
279         SubNetworkInstModel.objects.filter(instid=self.nf_inst_id).delete()
280         PortInstModel.objects.filter(instid=self.nf_inst_id).delete()
281         FlavourInstModel.objects.filter(instid=self.nf_inst_id).delete()
282         VmInstModel.objects.filter(instid=self.nf_inst_id).delete()
283         JobUtil.add_job_status(self.job_id, 255, 'Create resource failed')
284
285
286