Add code of grant resource
[vfc/gvnfm/vnflcm.git] / lcm / lcm / nf / vnfs / vnf_cancel / term_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 logging
15 import traceback
16 from threading import Thread
17
18 from lcm.nf.vnfs.const import VNF_STATUS
19 from lcm.pub.database.models import JobStatusModel, NfInstModel, VmInstModel, NetworkInstModel, StorageInstModel, \
20     FlavourInstModel, PortInstModel, SubNetworkInstModel, NfvoRegInfoModel
21 from lcm.pub.exceptions import NFLCMException
22 from lcm.pub.msapi.nfvolcm import apply_grant_to_nfvo
23 from lcm.pub.utils.jobutil import JobUtil
24 from lcm.pub.utils.values import ignore_case_get
25
26 logger = logging.getLogger(__name__)
27
28
29 class TermVnf(Thread):
30     def __init__(self, data, nf_inst_id, job_id):
31         super(TermVnf, self).__init__()
32         self.data = data
33         self.nf_inst_id = nf_inst_id
34         self.job_id = job_id
35         self.terminationType = ignore_case_get(self.data, "terminationType")
36         self.gracefulTerminationTimeout = ignore_case_get(self.data, "gracefulTerminationTimeout")
37         self.inst_resource = {'volumn': [],  # [{"vim_id": ignore_case_get(ret, "vim_id")},{}]
38                               'network': [],
39                               'subnet': [],
40                               'port': [],
41                               'flavor': [],
42                               'vm': [],
43                               }
44
45     def run(self):
46         try:
47             self.term_pre()
48             self.query_inst_resource(self.nf_inst_id)
49             # self.grant_resource()
50             JobUtil.add_job_status(self.job_id, 100, "Terminate Vnf success.")
51             is_exist = JobStatusModel.objects.filter(jobid=self.job_id).exists()
52             logger.debug("check_ns_inst_name_exist::is_exist=%s" % is_exist)
53         except NFLCMException as e:
54             logger.error('VNF instantiation failed, detail message: %s' % e.message)
55             # NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
56             JobUtil.add_job_status(self.job_id, 255, e.message)
57             # self.vnf_term_failed_handle(e.message)
58         except:
59             # self.vnf_term_failed_handle('unexpected exception')
60             logger.error(traceback.format_exc())
61
62     def term_pre(self):
63         vnf_insts = NfInstModel.objects.filter(pk=self.nf_inst_id)
64         if not vnf_insts.exists():
65             raise NFLCMException('VnfInst(%s) does not exist' % self.nf_inst_id)
66         sel_vnf = vnf_insts[0]
67         if sel_vnf.instantiationState != 'VNF_INSTANTIATED':
68             raise NFLCMException("No instantiated vnf")
69         if self.terminationType == 'GRACEFUL' and not self.gracefulTerminationTimeout:
70             raise NFLCMException("Graceful termination must set timeout")
71         # get nfvo info
72         JobUtil.add_job_status(self.job_id, 5, 'Get nfvo connection info')
73         self.load_nfvo_config()
74
75         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.TERMINATING)
76
77         JobUtil.add_job_status(self.job_id, 10, 'Nf terminating pre-check finish')
78         logger.info("Nf terminating pre-check finish")
79
80     def query_inst_resource(self, inst_id):
81         logger.info('[query_resource begin]:inst_id=%s' % inst_id)
82         # query_volumn_resource
83         vol_list = StorageInstModel.objects.filter(instid=inst_id,
84                                                    is_predefined=1)
85         for vol in vol_list:
86             vol_info = {}
87             if not vol.resouceid:
88                 continue
89             vol_info["res_id"] = vol.resouceid
90             vol_info["vim_id"] = vol.vimid
91             self.inst_resource['volumn'].append(vol_info)
92         logger.info('[query_volumn_resource]:ret_volumns=%s' % self.inst_resource['volumn'])
93
94         # query_network_resource
95         network_list = NetworkInstModel.objects.filter(instid=inst_id,
96                                                        is_predefined=1)
97         for network in network_list:
98             network_info = {}
99             if not network.resouceid:
100                 continue
101             network_info["res_id"] = network.resouceid
102             network_info["vim_id"] = network.vimid
103             self.inst_resource['network'].append(network_info)
104         logger.info('[query_network_resource]:ret_networks=%s' % self.inst_resource['network'])
105
106         # query_subnetwork_resource
107         subnetwork_list = SubNetworkInstModel.objects.filter(instid=inst_id,
108                                                        is_predefined=1)
109         for subnetwork in subnetwork_list:
110             subnetwork_info = {}
111             if not subnetwork.resouceid:
112                 continue
113             subnetwork_info["res_id"] = subnetwork.resouceid
114             subnetwork_info["vim_id"] = subnetwork.vimid
115             self.inst_resource['subnet'].append(subnetwork_info)
116         logger.info('[query_subnetwork_resource]:ret_networks=%s' % self.inst_resource['subnet'])
117
118         # query_port_resource
119         port_list = PortInstModel.objects.filter(instid=inst_id,
120                                                        is_predefined=1)
121         for port in port_list:
122             port_info = {}
123             if not port.resouceid:
124                 continue
125             port_info["res_id"] = port.resouceid
126             port_info["vim_id"] = port.vimid
127             self.inst_resource['port'].append(port_info)
128         logger.info('[query_port_resource]:ret_networks=%s' % self.inst_resource['port'])
129
130         # query_flavor_resource
131         flavor_list = FlavourInstModel.objects.filter(instid=inst_id,
132                                                        is_predefined=1)
133         for flavor in flavor_list:
134             flavor_info = {}
135             if not flavor.resouceid:
136                 continue
137             flavor_info["res_id"] = flavor.resouceid
138             flavor_info["vim_id"] = flavor.vimid
139             self.inst_resource['flavor'].append(flavor_info)
140         logger.info('[query_flavor_resource]:ret_networks=%s' % self.inst_resource['flavor'])
141
142         # query_vm_resource
143         vm_list = VmInstModel.objects.filter(instid=inst_id,
144                                              is_predefined=1)
145         for vm in vm_list:
146             vm_info = {}
147             if not vm.resouceid:
148                 continue
149             vm_info["res_id"] = vm.resouceid
150             vm_info["vim_id"] = vm.vimid
151             self.inst_resource['vm'].append(vm_info)
152         logger.info('[query_vm_resource]:ret_vms=%s' % self.inst_resource['vm'])
153
154     def grant_resource(self):
155         logger.info("nf_cancel_task grant_resource begin")
156         JobUtil.add_job_status(self.job_id, 30, 'nf_cancel_task grant_resource')
157         reg_info = NfvoRegInfoModel.objects.filter(vnfminstid=self.vnfm_inst_id).first()
158         nf_info = NfInstModel.objects.filter(nfinstid=self.vnf_inst_id).first()
159         content_args = {'nfvoInstanceId': reg_info.nfvoid, 'vnfmInstanceId': self.vnfm_inst_id,
160                         'nfInstanceId': self.vnf_inst_id, 'nfDescriptorId': nf_info.vnf_id,
161                         'lifecycleOperation': 'Terminal', 'jobId': '', 'addResource': [],
162                         'removeResource': [], 'placementConstraint': [], 'exVimIdList': [], 'additionalParam': {}}
163
164         content_args['removeResource'] = self.get_grant_data()
165
166         logger.info('content_args=%s' % content_args)
167         rsp = apply_grant_to_nfvo(content_args)
168         logger.info("nf_cancel_task grant_resource rsp: %s" % rsp)
169         if rsp[0] != 0:
170             logger.error("nf_cancel_task grant_resource failed.[%s]" % str(rsp[1]))
171         logger.info("nf_cancel_task grant_resource end")
172
173     def load_nfvo_config(self):
174         logger.info("[NF instantiation]get nfvo connection info start")
175         reg_info = NfvoRegInfoModel.objects.filter(vnfminstid='vnfm111').first()
176         if reg_info:
177             self.vnfm_inst_id = reg_info.vnfminstid
178             self.nfvo_inst_id = reg_info.nfvoid
179             logger.info("[NF instantiation] Registered nfvo id is [%s]" % self.nfvo_inst_id)
180         else:
181             raise NFLCMException("Nfvo was not registered")
182         logger.info("[NF instantiation]get nfvo connection info end")