9340a735a9098f1fd78a9084baad91e468869308
[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
20 from lcm.pub.exceptions import NFLCMException
21 from lcm.pub.msapi.nfvolcm import vnfd_rawdata_get, apply_grant_to_nfvo
22 from lcm.pub.utils.jobutil import JobUtil
23 from lcm.pub.utils.timeutil import now_time
24
25 logger = logging.getLogger(__name__)
26
27
28 class InstVnf(Thread):
29     def __init__(self, data, nf_inst_id, job_id):
30         super(InstVnf, self).__init__()
31         self.data = data
32         self.nf_inst_id = nf_inst_id
33         self.job_id = job_id
34         self.nfvo_inst_id = ''
35         self.vnfm_inst_id = ''
36
37     def run(self):
38         try:
39             self.inst_pre()
40             self.apply_grant()
41             # self.apply_res(args)
42             # self.check_res_status(args)
43             # self.wait_inst_finish(args)
44             # self.lcm_notify(args)
45             JobUtil.add_job_status(self.job_id, 100, "Instantiate Vnf success.")
46             is_exist = JobStatusModel.objects.filter(jobid=self.job_id).exists()
47             logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
48         except NFLCMException as e:
49             self.vnf_inst_failed_handle(e.message)
50             # self.rollback(e.message)
51         except:
52             self.vnf_inst_failed_handle('unexpected exception')
53             logger.error(traceback.format_exc())
54             # self.rollback('unexpected exception')
55
56     def inst_pre(self):
57         vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
58         if not vnf_insts.exists():
59             raise NFLCMException('VNF nf_inst_id is not exist.')
60
61         self.vnfm_inst_id = vnf_insts[0].vnfm_inst_id
62         if vnf_insts[0].instantiationState != 'NOT_INSTANTIATED':
63             raise NFLCMException('VNF instantiationState is not NOT_INSTANTIATED.')
64
65         #get rawdata by vnfd_id
66         ret = vnfd_rawdata_get(vnf_insts[0].vnfdid)
67         if ret[0] != 0:
68             raise NFLCMException("Get vnfd_raw_data failed.")
69         self.vnfd_info = json.JSONDecoder().decode(ret[1])
70         #checkParameterExist
71         for cp in self.data:
72             if cp not in self.vnfd_info:
73                 raise NFLCMException('Input parameter is not defined in vnfd_info.')
74         #get nfvo info
75         JobUtil.add_job_status(self.job_id, 5, 'GET_NFVO_CONNECTION_INFO')
76         self.load_nfvo_config()
77
78     def apply_grant(self):
79         logger.info('[NF instantiation] send resource grand request to nfvo start')
80         #self.check_vm_capacity()
81         content_args = {'nfvoInstanceId': self.nfvo_inst_id, 'vnfmInstanceId': self.vnfm_inst_id,
82                         'nfInstanceId': self.nf_inst_id, 'nfDescriptorId': '',
83                         'lifecycleOperation': 'Instantiate', 'jobId': self.job_id, 'addResource': [],
84                         'removeResource': [], 'placementConstraint': [], 'exVimIdList': [], 'additionalParam': {}}
85
86         vdus = self.vnfd_info['vdus']
87         res_index = 1
88         for vdu in vdus:
89             res_def = {'type': 'VDU', 'resourceDefinitionId': str(res_index), 'vduId': vdu['vdu_id'],
90                        'vimid': '', 'tenant': ''}
91             if self.vnfd_info['metadata']['cross_dc']:
92                 res_def['vimid'] = vdu['properties']['location_info']['vimId']
93                 res_def['tenant'] = vdu['properties']['location_info']['tenant']
94             content_args['addResource'].append(res_def)
95             res_index += 1
96         logger.info('content_args=%s' % content_args)
97         resp = apply_grant_to_nfvo(content_args)
98         logger.info("[NF instantiation] get grant response = %s" % resp)
99         if resp[0] != 0:
100             raise NFLCMException('Nf instancing apply grant exception')
101
102         #update_resources_table()
103         JobUtil.add_job_status(self.job_id, 15, 'Nf instancing apply grant finish')
104         logger.info("Nf instancing apply grant finish")
105
106     def apply_res(self, args):
107         try:
108             logger.info('apply_res, args=%s' % args)
109             # ApplyResTask(args).do_biz()
110             return {'result': '100', 'msg': 'Nf instancing apply resource finish', 'context': {}}
111         except Exception as e:
112             logger.error('Nf instancing apply resource exception=%s' % e.message)
113             logger.error(traceback.format_exc())
114             return {'result': '255', 'msg': 'Nf instancing apply resource exception', 'context': {}}
115
116     def check_res_status(self, args):
117         try:
118             logger.info('check_res_status, args=%s' % args)
119             # CheckResStatusTask(args).do_biz()
120             return {'result': '100', 'msg': 'Nf instancing check resource status finish', 'context': {}}
121         except Exception as e:
122             logger.error('Nf instancing check resource status exception=%s' % e.message)
123             logger.error(traceback.format_exc())
124             return {'result': '255', 'msg': 'Nf instancing check resource status exception', 'context': {}}
125
126     def wait_inst_finish(self, args):
127         try:
128             logger.info('wait_inst_finish, args=%s' % args)
129             # WaitInstFinishTask(args).do_biz()
130             return {'result': '100', 'msg': 'Nf instancing wait finish', 'context': {}}
131         except Exception as e:
132             logger.error('Nf instancing wait exception=%s' % e.message)
133             logger.error(traceback.format_exc())
134             return {'result': '255', 'msg': 'Nf instancing wait exception', 'context': {}}
135
136     def lcm_notify(self, args):
137         try:
138             logger.info('lcm_notify, args=%s' % args)
139             # LcmNotifyTask(args).do_biz()
140             return {'result': '100', 'msg': 'Nf instancing lcm notify finish', 'context': {}}
141         except Exception as e:
142             logger.error('Nf instancing lcm notify exception=%s' % e.message)
143             logger.error(traceback.format_exc())
144             return {'result': '255', 'msg': 'Nf instancing lcm notify exception', 'context': {}}
145
146     def rollback(self, args):
147         try:
148             logger.info('inst_exception, args=%s' % args)
149             # InstExceptionTask(args).do_biz()
150             return {'result': '100', 'msg': 'Nf instancing exception process finish', 'context': {}}
151         except Exception as e:
152             logger.error('Nf instancing exception process exception=%s' % e.message)
153             logger.error(traceback.format_exc())
154             return {'result': '255', 'msg': 'Nf instancing exception process exception', 'context': {}}
155
156     def load_nfvo_config(self):
157         logger.info("[NF instantiation]get nfvo connection info start")
158         reg_info = NfvoRegInfoModel.objects.filter(vnfminstid='vnfm111').first()
159         if reg_info:
160             self.nfvo_inst_id = reg_info.nfvoid
161             logger.info("[NF instantiation] Registered nfvo id is [%s]"%self.nfvo_inst_id)
162         else:
163             raise NFLCMException("Nfvo was not registered")
164         logger.info("[NF instantiation]get nfvo connection info end")
165
166     def vnf_inst_failed_handle(self, error_msg):
167         logger.error('VNF instantiation failed, detail message: %s' % error_msg)
168         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
169         JobUtil.add_job_status(self.job_id, 255, error_msg)
170         # JobUtil.add_job_status(self.job_id, 255, 'VNF instantiation failed, detail message: %s' % error_msg, 0)
171