Save vnfc to DB
[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
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
62                 }
63
64             }
65         }
66
67     def run(self):
68         try:
69             self.inst_pre()
70             self.apply_grant()
71             self.create_res()
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)
81         except:
82             # self.vnf_inst_failed_handle('unexpected exception')
83             logger.error(traceback.format_exc())
84             # self.rollback('unexpected exception')
85
86     def inst_pre(self):
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.')
90
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.')
94
95         #get rawdata by vnfd_id
96         ret = vnfd_rawdata_get(vnf_insts[0].vnfdid)
97         if ret[0] != 0:
98             raise NFLCMException("Get vnfd_raw_data failed.")
99         self.vnfd_info = json.JSONDecoder().decode(ret[1])
100         #checkParameterExist
101         for cp in self.data:
102             if cp not in self.vnfd_info:
103                 raise NFLCMException('Input parameter is not defined in vnfd_info.')
104         #get nfvo info
105         JobUtil.add_job_status(self.job_id, 5, 'GET_NFVO_CONNECTION_INFO')
106         self.load_nfvo_config()
107
108         #update NfInstModel
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())
116
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': {}}
124
125         vdus = self.vnfd_info['vdus']
126         res_index = 1
127         for vdu in 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)
134             res_index += 1
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)
138         if resp[0] != 0:
139             raise NFLCMException('Nf instancing apply grant exception')
140
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")
145
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')
151
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')
155
156         vdus = ignore_case_get(self.data, "vdus")
157         # create_vdus(vdus)
158         JobUtil.add_job_status(self.job_id, 75, 'Nf instancing create resource(vms) finish')
159
160         logger.info("[NF instantiation] create resource end")
161
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']
165         for vnfc in vnfcs:
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'])
169
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']
173
174         for vnfc in vnfcs:
175             if 'failed' == vnfc['status']:
176                 continue
177             compute_resource = vnfc['computeresource']
178             vminst = VmInstModel.objects.filter(resouceid=compute_resource['resourceid']).first()
179             VNFCInstModel.objects.create(
180                 vnfcinstanceid=vnfc['vnfcinstanceid'],
181                 vduid=vnfc['vduid'],
182                 vdutype=vnfc['vdutype'],
183                 nfinstid=self.nf_inst_id,
184                 vmid=vminst.vmid)
185         for vl in vls:
186             if 'failed' == vl['status']:
187                 continue
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',
196                 ownerid=self.nf_inst_id,
197                 relatednetworkid=networkinst.networkid,
198                 relatedsubnetworkid=subnetinst.subnetworkid)
199         pass
200         # # for vs in vss:
201         # for cp in cps:
202         #     if 'failed' == cp['status']:
203         #         continue
204         #     port_resource = cp['portresource']
205         #     portinst = PortInstModel.objects.filter(resouceid=port_resource['resourceid']).first()
206         #     CPInstModel.objects.create(
207         #         cpinstanceid=cp['cpinstanceid'],
208         #         cpdid=cp['cpdid'],
209         #         relatedtype='2',  # port
210         #         relatedport=portinst.portid,
211         #         ownertype=cp['ownertype'],
212         #         ownerid=cp['ownerid'],
213         #         vlinstanceid=cp['virtuallinkinstanceid'])
214         # self.add_job(43, 'INST_DPLY_VM_PRGS')
215         logger.info("[NF instantiation] confirm all vms are active end")
216
217     def wait_inst_finish(self, args):
218         try:
219             logger.info('wait_inst_finish, args=%s' % args)
220             # WaitInstFinishTask(args).do_biz()
221             return {'result': '100', 'msg': 'Nf instancing wait finish', 'context': {}}
222         except Exception as e:
223             logger.error('Nf instancing wait exception=%s' % e.message)
224             logger.error(traceback.format_exc())
225             return {'result': '255', 'msg': 'Nf instancing wait exception', 'context': {}}
226
227     def lcm_notify(self, args):
228         try:
229             logger.info('lcm_notify, args=%s' % args)
230             # LcmNotifyTask(args).do_biz()
231             return {'result': '100', 'msg': 'Nf instancing lcm notify finish', 'context': {}}
232         except Exception as e:
233             logger.error('Nf instancing lcm notify exception=%s' % e.message)
234             logger.error(traceback.format_exc())
235             return {'result': '255', 'msg': 'Nf instancing lcm notify exception', 'context': {}}
236
237     def rollback(self, args):
238         try:
239             logger.info('inst_exception, args=%s' % args)
240             # InstExceptionTask(args).do_biz()
241             return {'result': '100', 'msg': 'Nf instancing exception process finish', 'context': {}}
242         except Exception as e:
243             logger.error('Nf instancing exception process exception=%s' % e.message)
244             logger.error(traceback.format_exc())
245             return {'result': '255', 'msg': 'Nf instancing exception process exception', 'context': {}}
246
247     def load_nfvo_config(self):
248         logger.info("[NF instantiation]get nfvo connection info start")
249         reg_info = NfvoRegInfoModel.objects.filter(vnfminstid='vnfm111').first()
250         if reg_info:
251             self.nfvo_inst_id = reg_info.nfvoid
252             logger.info("[NF instantiation] Registered nfvo id is [%s]"%self.nfvo_inst_id)
253         else:
254             raise NFLCMException("Nfvo was not registered")
255         logger.info("[NF instantiation]get nfvo connection info end")
256
257     def vnf_inst_failed_handle(self, error_msg):
258         logger.error('VNF instantiation failed, detail message: %s' % error_msg)
259         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
260         JobUtil.add_job_status(self.job_id, 255, error_msg)
261         # JobUtil.add_job_status(self.job_id, 255, 'VNF instantiation failed, detail message: %s' % error_msg, 0)
262
263