VNF Deployment
[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 from lcm.pub.exceptions import NFLCMException
21 from lcm.pub.msapi.nfvolcm import vnfd_rawdata_get, apply_grant_to_nfvo, apply_res_to_nfvo
22 from lcm.pub.utils.jobutil import JobUtil
23 from lcm.pub.utils.timeutil import now_time
24 from lcm.pub.utils.values import ignore_case_get
25
26 logger = logging.getLogger(__name__)
27
28
29 class InstVnf(Thread):
30     def __init__(self, data, nf_inst_id, job_id):
31         super(InstVnf, self).__init__()
32         self.data = data
33         self.nf_inst_id = nf_inst_id
34         self.job_id = job_id
35         self.nfvo_inst_id = ''
36         self.vnfm_inst_id = ''
37         self.create_res_result = {
38             'jobid': 'res_001',
39             'resourceResult': [{'name': 'vm01'}, {'name': 'vm02'}],
40             'resource_result':{
41                 'affectedvnfc':[
42                     {
43                         'status':'success',
44                         'vnfcinstanceid':'1',
45                         'computeresource':{'resourceid':'11'},
46                         'vduid':'111',
47                         'vdutype':'1111'
48                     },
49                     {
50                         'status': 'success',
51                         'vnfcinstanceid': '2',
52                         'computeresource': {'resourceid':'22'},
53                         'vduid': '222',
54                         'vdutype': '2222'
55                     }
56                 ],
57                 'affectedvirtuallink':{
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',  # VNF
196         #         ownerid=self.nf_inst_id,
197         #         relatednetworkid=networkinst.networkid,
198         #         relatedsubnetworkid=subnetinst.subnetworkid)
199         # # for vs in vss:
200         # for cp in cps:
201         #     if 'failed' == cp['status']:
202         #         continue
203         #     port_resource = cp['portresource']
204         #     portinst = PortInstModel.objects.filter(resouceid=port_resource['resourceid']).first()
205         #     CPInstModel.objects.create(
206         #         cpinstanceid=cp['cpinstanceid'],
207         #         cpdid=cp['cpdid'],
208         #         relatedtype='2',  # port
209         #         relatedport=portinst.portid,
210         #         ownertype=cp['ownertype'],
211         #         ownerid=cp['ownerid'],
212         #         vlinstanceid=cp['virtuallinkinstanceid'])
213         # self.add_job(43, 'INST_DPLY_VM_PRGS')
214         logger.info("[NF instantiation] confirm all vms are active end")
215
216     def wait_inst_finish(self, args):
217         try:
218             logger.info('wait_inst_finish, args=%s' % args)
219             # WaitInstFinishTask(args).do_biz()
220             return {'result': '100', 'msg': 'Nf instancing wait finish', 'context': {}}
221         except Exception as e:
222             logger.error('Nf instancing wait exception=%s' % e.message)
223             logger.error(traceback.format_exc())
224             return {'result': '255', 'msg': 'Nf instancing wait exception', 'context': {}}
225
226     def lcm_notify(self, args):
227         try:
228             logger.info('lcm_notify, args=%s' % args)
229             # LcmNotifyTask(args).do_biz()
230             return {'result': '100', 'msg': 'Nf instancing lcm notify finish', 'context': {}}
231         except Exception as e:
232             logger.error('Nf instancing lcm notify exception=%s' % e.message)
233             logger.error(traceback.format_exc())
234             return {'result': '255', 'msg': 'Nf instancing lcm notify exception', 'context': {}}
235
236     def rollback(self, args):
237         try:
238             logger.info('inst_exception, args=%s' % args)
239             # InstExceptionTask(args).do_biz()
240             return {'result': '100', 'msg': 'Nf instancing exception process finish', 'context': {}}
241         except Exception as e:
242             logger.error('Nf instancing exception process exception=%s' % e.message)
243             logger.error(traceback.format_exc())
244             return {'result': '255', 'msg': 'Nf instancing exception process exception', 'context': {}}
245
246     def load_nfvo_config(self):
247         logger.info("[NF instantiation]get nfvo connection info start")
248         reg_info = NfvoRegInfoModel.objects.filter(vnfminstid='vnfm111').first()
249         if reg_info:
250             self.nfvo_inst_id = reg_info.nfvoid
251             logger.info("[NF instantiation] Registered nfvo id is [%s]"%self.nfvo_inst_id)
252         else:
253             raise NFLCMException("Nfvo was not registered")
254         logger.info("[NF instantiation]get nfvo connection info end")
255
256     def vnf_inst_failed_handle(self, error_msg):
257         logger.error('VNF instantiation failed, detail message: %s' % error_msg)
258         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
259         JobUtil.add_job_status(self.job_id, 255, error_msg)
260         # JobUtil.add_job_status(self.job_id, 255, 'VNF instantiation failed, detail message: %s' % error_msg, 0)
261
262