Deal with gvnfm adapter stuffs.
[vfc/gvnfm/vnflcm.git] / lcm / lcm / nf / biz / terminate_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
15 import json
16 import logging
17 import traceback
18 from threading import Thread
19
20 from lcm.nf.const import VNF_STATUS, RESOURCE_MAP
21 from lcm.pub.database.models import (
22     NfInstModel, VmInstModel, NetworkInstModel,
23     StorageInstModel, PortInstModel, VNFCInstModel,
24     FlavourInstModel, SubNetworkInstModel
25 )
26 from lcm.pub.exceptions import NFLCMException
27 from lcm.pub.msapi.gvnfmdriver import prepare_notification_data, notify_lcm_to_nfvo
28 from lcm.pub.utils.jobutil import JobUtil
29 from lcm.pub.utils.timeutil import now_time
30 from lcm.pub.utils.values import ignore_case_get
31 from lcm.pub.vimapi import adaptor
32 from lcm.nf.biz.grant_vnf import grant_resource
33
34 logger = logging.getLogger(__name__)
35
36
37 class TerminateVnf(Thread):
38     def __init__(self, data, nf_inst_id, job_id):
39         super(TerminateVnf, self).__init__()
40         self.data = data
41         self.nf_inst_id = nf_inst_id
42         self.job_id = job_id
43         self.terminationType = ignore_case_get(self.data, "terminationType")
44         self.gracefulTerminationTimeout = ignore_case_get(self.data, "gracefulTerminationTimeout")
45         self.inst_resource = {'volumn': [], 'network': [], 'subnet': [], 'port': [], 'flavor': [], 'vm': []}
46         self.grant_type = "Terminate"
47
48     def run(self):
49         try:
50             if self.term_pre():
51                 vdus = VmInstModel.objects.filter(instid=self.nf_inst_id, is_predefined=1)
52                 apply_result = grant_resource(data=self.data, nf_inst_id=self.nf_inst_id, job_id=self.job_id,
53                                               grant_type=self.grant_type, vdus=vdus)
54                 logger.info("Grant resource end, response: %s" % apply_result)
55                 JobUtil.add_job_status(self.job_id, 20, 'Nf terminating grant_resource finish')
56                 self.query_inst_resource()
57                 self.query_notify_data()
58                 self.delete_resource()
59                 self.lcm_notify()
60             JobUtil.add_job_status(self.job_id, 100, "Terminate Vnf success.")
61         except NFLCMException as e:
62             self.vnf_term_failed_handle(e.message)
63         except Exception as e:
64             logger.error(e.message)
65             self.vnf_term_failed_handle(traceback.format_exc())
66
67     def term_pre(self):
68         vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
69         if not vnf_insts.exists():
70             logger.warn('VnfInst(%s) does not exist' % self.nf_inst_id)
71             return False
72         if self.terminationType == 'GRACEFUL' and not self.gracefulTerminationTimeout:
73             logger.warn("Set Graceful default termination timeout = 60")
74             self.gracefulTerminationTimeout = 60
75         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.TERMINATING)
76         JobUtil.add_job_status(self.job_id, 10, 'Nf terminating pre-check finish')
77         logger.info("Nf terminating pre-check finish")
78         return True
79
80     def query_inst_resource(self):
81         logger.info('Query resource begin')
82         for resource_type in RESOURCE_MAP.keys():
83             resource_table = globals().get(resource_type + 'InstModel')
84             resource_insts = resource_table.objects.filter(instid=self.nf_inst_id)
85             for resource_inst in resource_insts:
86                 if not resource_inst.resouceid:
87                     continue
88                 self.inst_resource[RESOURCE_MAP.get(resource_type)].append(self.get_resource(resource_inst))
89         logger.info('Query resource end, resource=%s' % self.inst_resource)
90
91     def get_resource(self, resource):
92         return {
93             "vim_id": resource.vimid,
94             "tenant_id": resource.tenant,
95             "res_id": resource.resouceid,
96             "is_predefined": resource.is_predefined
97         }
98
99     def query_notify_data(self):
100         self.notify_data = prepare_notification_data(self.nf_inst_id, self.job_id, "RMOVED")
101         NetworkInstModel.objects.filter(instid=self.nf_inst_id)
102         StorageInstModel.objects.filter(instid=self.nf_inst_id)
103         PortInstModel.objects.filter(instid=self.nf_inst_id)
104         VNFCInstModel.objects.filter(instid=self.nf_inst_id)
105         FlavourInstModel.objects.filter(instid=self.nf_inst_id)
106         SubNetworkInstModel.objects.filter(instid=self.nf_inst_id)
107
108     def delete_resource(self):
109         logger.info('Rollback resource begin')
110         adaptor.delete_vim_res(self.inst_resource, self.do_notify_delete)
111         logger.info('Rollback resource complete')
112
113     def do_notify_delete(self, res_type, res_id):
114         logger.error('Deleting [%s] resource, resourceid [%s]' % (res_type, res_id))
115         resource_type = RESOURCE_MAP.keys()[RESOURCE_MAP.values().index(res_type)]
116         resource_table = globals().get(resource_type + 'InstModel')
117         resource_table.objects.filter(instid=self.nf_inst_id, resouceid=res_id).delete()
118
119     def lcm_notify(self):
120         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='NOT_INSTANTIATED', lastuptime=now_time())
121         logger.info('Send notify request to nfvo')
122         resp = notify_lcm_to_nfvo(json.dumps(self.notify_data))
123         logger.info('Lcm notify end, response: %s' % resp)
124
125     def vnf_term_failed_handle(self, error_msg):
126         logger.error('VNF termination failed, detail message: %s' % error_msg)
127         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
128         JobUtil.add_job_status(self.job_id, 255, error_msg)