Update cp table after create resource
[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
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
27 logger = logging.getLogger(__name__)
28
29
30 class InstVnf(Thread):
31     def __init__(self, data, nf_inst_id, job_id):
32         super(InstVnf, self).__init__()
33         self.data = data
34         self.nf_inst_id = nf_inst_id
35         self.job_id = job_id
36         self.nfvo_inst_id = ''
37         self.vnfm_inst_id = ''
38         self.create_res_result = {
39             'jobid': 'res_001',
40             'resourceResult': [{'name': 'vm01'}, {'name': 'vm02'}],
41             'resource_result':{
42                 'affectedvnfc':[
43                     {
44                         'status':'success',
45                         'vnfcinstanceid':'1',
46                         'computeresource':{'resourceid':'11'},
47                         'vduid':'111',
48                         'vdutype':'1111'
49                     }
50                 ],
51                 'affectedvirtuallink':[
52                     {
53                         'status': 'success',
54                         'virtuallinkinstanceid':'',
55                         'networkresource':{'resourceid':'1'},
56                         'subnetworkresource':{'resourceid':'1'},
57                         'virtuallinkdescid': '',
58                     }
59                 ],
60                 'affectedcp':[{
61                     'status': 'success',
62                     'portresource':{'resourceid':'1'},
63                     'cpinstanceid':'2',
64                     'cpdid':'22',
65                     'ownertype':'222',
66                     'ownerid':'2222',
67                     'virtuallinkinstanceid':'22222',
68
69                 }],
70
71             }
72         }
73
74     def run(self):
75         try:
76             self.inst_pre()
77             self.apply_grant()
78             self.create_res()
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)
88         except:
89             # self.vnf_inst_failed_handle('unexpected exception')
90             logger.error(traceback.format_exc())
91             # self.rollback('unexpected exception')
92
93     def inst_pre(self):
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.')
97
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.')
101
102         #get rawdata by vnfd_id
103         ret = vnfd_rawdata_get(vnf_insts[0].vnfdid)
104         if ret[0] != 0:
105             raise NFLCMException("Get vnfd_raw_data failed.")
106         self.vnfd_info = json.JSONDecoder().decode(ret[1])
107         #checkParameterExist
108         for cp in self.data:
109             if cp not in self.vnfd_info:
110                 raise NFLCMException('Input parameter is not defined in vnfd_info.')
111         #get nfvo info
112         JobUtil.add_job_status(self.job_id, 5, 'GET_NFVO_CONNECTION_INFO')
113         self.load_nfvo_config()
114
115         #update NfInstModel
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())
123
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': {}}
131
132         vdus = self.vnfd_info['vdus']
133         res_index = 1
134         for vdu in 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)
141             res_index += 1
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)
145         if resp[0] != 0:
146             raise NFLCMException('Nf instancing apply grant exception')
147
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")
152
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')
159
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')
163
164         vdus = ignore_case_get(self.data, "vdus")
165         # create_vdus(vdus)
166         JobUtil.add_job_status(self.job_id, 75, 'Nf instancing create resource(vms) finish')
167
168         logger.info("[NF instantiation] create resource end")
169
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']
173         for vnfc in vnfcs:
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'])
177
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']
181
182         for vnfc in vnfcs:
183             if 'failed' == vnfc['status']:
184                 continue
185             compute_resource = vnfc['computeresource']
186             vminst = VmInstModel.objects.filter(resouceid=compute_resource['resourceid']).first()
187             VNFCInstModel.objects.create(
188                 vnfcinstanceid=vnfc['vnfcinstanceid'],
189                 vduid=vnfc['vduid'],
190                 vdutype=vnfc['vdutype'],
191                 nfinstid=self.nf_inst_id,
192                 vmid=vminst.vmid)
193         for vl in vls:
194             if 'failed' == vl['status']:
195                 continue
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'],
203                 ownertype='0',
204                 ownerid=self.nf_inst_id,
205                 relatednetworkid=networkinst.networkid,
206                 relatedsubnetworkid=subnetinst.subnetworkid)
207         # # for vs in vss:
208         for cp in cps:
209             if 'failed' == cp['status']:
210                 continue
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'],
216                 cpdid=cp['cpdid'],
217                 relatedtype='2',
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")
224
225     def wait_inst_finish(self, args):
226         try:
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': {}}
234
235     def lcm_notify(self, args):
236         try:
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': {}}
244
245     def rollback(self, args):
246         try:
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': {}}
254
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()
258         if reg_info:
259             self.nfvo_inst_id = reg_info.nfvoid
260             logger.info("[NF instantiation] Registered nfvo id is [%s]"%self.nfvo_inst_id)
261         else:
262             raise NFLCMException("Nfvo was not registered")
263         logger.info("[NF instantiation]get nfvo connection info end")
264
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)
270
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, '')
274
275