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