1fc0506c03423a18d2b069d9796d3afec17eaec1
[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 NfInstModel, VmInstModel, NetworkInstModel, StorageInstModel, \
22     PortInstModel, VNFCInstModel, FlavourInstModel, SubNetworkInstModel
23 from lcm.pub.exceptions import NFLCMException
24 from lcm.pub.msapi.gvnfmdriver import apply_grant_to_nfvo, notify_lcm_to_nfvo
25 from lcm.pub.utils.jobutil import JobUtil
26 from lcm.pub.utils.timeutil import now_time
27 from lcm.pub.utils.values import ignore_case_get
28 from lcm.pub.vimapi import adaptor
29
30 logger = logging.getLogger(__name__)
31
32
33 class TerminateVnf(Thread):
34     def __init__(self, data, nf_inst_id, job_id):
35         super(TerminateVnf, self).__init__()
36         self.data = data
37         self.nf_inst_id = nf_inst_id
38         self.job_id = job_id
39         self.terminationType = ignore_case_get(self.data, "terminationType")
40         self.gracefulTerminationTimeout = ignore_case_get(self.data, "gracefulTerminationTimeout")
41         self.inst_resource = {'volumn': [], 'network': [], 'subnet': [], 'port': [], 'flavor': [], 'vm': []}
42
43     def run(self):
44         try:
45             if self.term_pre():
46                 self.grant_resource()
47                 self.query_inst_resource()
48                 self.query_notify_data()
49                 self.delete_resource()
50                 self.lcm_notify()
51             JobUtil.add_job_status(self.job_id, 100, "Terminate Vnf success.")
52         except NFLCMException as e:
53             self.vnf_term_failed_handle(e.message)
54         except Exception as e:
55             logger.error(e.message)
56             self.vnf_term_failed_handle(traceback.format_exc())
57
58     def term_pre(self):
59         vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
60         if not vnf_insts.exists():
61             logger.warn('VnfInst(%s) does not exist' % self.nf_inst_id)
62             return False
63         if self.terminationType == 'GRACEFUL' and not self.gracefulTerminationTimeout:
64             logger.warn("Set Graceful default termination timeout = 60")
65             self.gracefulTerminationTimeout = 60
66         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.TERMINATING)
67         JobUtil.add_job_status(self.job_id, 10, 'Nf terminating pre-check finish')
68         logger.info("Nf terminating pre-check finish")
69         return True
70
71     def grant_resource(self):
72         logger.info("Grant resource begin")
73         content_args = {
74             'vnfInstanceId': self.nf_inst_id,
75             'vnfDescriptorId': '',
76             'lifecycleOperation': 'Terminate',
77             'vnfLcmOpOccId': self.job_id,
78             'addResource': [],
79             'removeResource': [],
80             'placementConstraint': [],
81             'additionalParam': {}
82         }
83
84         vdus = VmInstModel.objects.filter(instid=self.nf_inst_id, is_predefined=1)
85         res_index = 1
86         for vdu in vdus:
87             res_def = {
88                 'type': 'VDU',
89                 'resDefId': str(res_index),
90                 'resDesId': vdu.resouceid}
91             content_args['removeResource'].append(res_def)
92             res_index += 1
93
94         vnfInsts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
95         content_args['additionalParam']['vnfmid'] = vnfInsts[0].vnfminstid
96         content_args['additionalParam']['vimid'] = vdus[0].vimid
97         logger.info('Grant request data=%s' % content_args)
98         self.apply_result = apply_grant_to_nfvo(json.dumps(content_args))
99         logger.info("Grant resource end, response: %s" % self.apply_result)
100         JobUtil.add_job_status(self.job_id, 20, 'Nf terminating grant_resource finish')
101
102     def query_inst_resource(self):
103         logger.info('Query resource begin')
104         for resource_type in RESOURCE_MAP.keys():
105             resource_table = globals().get(resource_type + 'InstModel')
106             resource_insts = resource_table.objects.filter(instid=self.nf_inst_id)
107             for resource_inst in resource_insts:
108                 if not resource_inst.resouceid:
109                     continue
110                 self.inst_resource[RESOURCE_MAP.get(resource_type)].append(self.get_resource(resource_inst))
111         logger.info('Query resource end, resource=%s' % self.inst_resource)
112
113     def get_resource(self, resource):
114         return {
115             "vim_id": resource.vimid,
116             "tenant_id": resource.tenant,
117             "res_id": resource.resouceid,
118             "is_predefined": resource.is_predefined
119         }
120
121     def query_notify_data(self):
122         logger.info('Send notify request to nfvo')
123         affected_vnfc = []
124         vnfcs = VNFCInstModel.objects.filter(instid=self.nf_inst_id)
125         for vnfc in vnfcs:
126             vm_resource = {}
127             if vnfc.vmid:
128                 vm = VmInstModel.objects.filter(vmid=vnfc.vmid)
129                 if vm:
130                     vm_resource = {'vimId': vm[0].vimid, 'resourceId': vm[0].resouceid,
131                                    'resourceName': vm[0].vmname, 'resourceType': 'vm'}
132             affected_vnfc.append(
133                 {'vnfcInstanceId': vnfc.vnfcinstanceid,
134                  'vduId': vnfc.vduid,
135                  'changeType': 'removed',
136                  'computeResource': vm_resource})
137         affected_vl = []
138         networks = NetworkInstModel.objects.filter(instid=self.nf_inst_id)
139         for network in networks:
140             network_resource = {
141                 'vimId': network.vimid,
142                 'resourceId': network.resouceid,
143                 'resourceName': network.name,
144                 'resourceType': 'network'}
145             affected_vl.append(
146                 {'vlInstanceId': network.networkid,
147                  'vldid': network.nodeId,
148                  'changeType': 'removed',
149                  'networkResource': network_resource})
150         affected_cp = []
151         ports = PortInstModel.objects.filter(instid=self.nf_inst_id)
152         for port in ports:
153             affected_cp.append(
154                 {'vsInstanceId': port.portid,
155                  'cpdid': port.nodeId,
156                  'changeType': 'removed',
157                  'storageResource': {'vimId': port.vimid, 'resourceId': port.resouceid,
158                                      'resourceName': port.name, 'resourceType': 'port'}})
159         affected_vs = []
160         vss = StorageInstModel.objects.filter(instid=self.nf_inst_id)
161         for vs in vss:
162             affected_vs.append(
163                 {'vsInstanceId': vs.storageid,
164                  'vsdId': vs.nodeId,
165                  'changeType': 'removed',
166                  'storageResource': {'vimId': vs.vimid, 'resourceId': vs.resouceid,
167                                      'resourceName': vs.name, 'resourceType': 'volume'}})
168         FlavourInstModel.objects.filter(instid=self.nf_inst_id)
169         SubNetworkInstModel.objects.filter(instid=self.nf_inst_id)
170         self.notify_data = {
171             "status": 'result',
172             "vnfInstanceId": self.nf_inst_id,
173             "operation": 'Terminal',
174             "jobId": self.job_id,
175             'affectedVnfc': affected_vnfc,
176             'affectedVirtualLink': affected_vl,
177             'affectedVirtualStorage': affected_vs,
178             'affectedCp': affected_cp}
179
180         vnfInsts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
181         self.notify_data['VNFMID'] = vnfInsts[0].vnfminstid
182         logger.info('Notify request data=%s' % self.notify_data)
183
184     def delete_resource(self):
185         logger.info('Rollback resource begin')
186         adaptor.delete_vim_res(self.inst_resource, self.do_notify_delete)
187         logger.info('Rollback resource complete')
188
189     def do_notify_delete(self, res_type, res_id):
190         logger.error('Deleting [%s] resource, resourceid [%s]' % (res_type, res_id))
191         resource_type = RESOURCE_MAP.keys()[RESOURCE_MAP.values().index(res_type)]
192         resource_table = globals().get(resource_type + 'InstModel')
193         resource_table.objects.filter(instid=self.nf_inst_id, resouceid=res_id).delete()
194
195     def lcm_notify(self):
196         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='NOT_INSTANTIATED', lastuptime=now_time())
197         logger.info('Send notify request to nfvo')
198         resp = notify_lcm_to_nfvo(json.dumps(self.notify_data))
199         logger.info('Lcm notify end, response: %s' % resp)
200
201     def vnf_term_failed_handle(self, error_msg):
202         logger.error('VNF termination failed, detail message: %s' % error_msg)
203         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
204         JobUtil.add_job_status(self.job_id, 255, error_msg)