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 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             'jobId': 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_vnfcs = []
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 = {
131                         'vimId': vm[0].vimid,
132                         'resourceId': vm[0].resouceid,
133                         'resourceProviderId': vm[0].vmname,
134                         'vimLevelResourceType': 'vm'
135                     }
136             affected_vnfcs.append({
137                 'id': vnfc.vnfcinstanceid,
138                 'vduId': vnfc.vduid,
139                 'changeType': 'REMOVED',
140                 'computeResource': vm_resource
141             })
142         affected_vls = []
143         networks = NetworkInstModel.objects.filter(instid=self.nf_inst_id)
144         for network in networks:
145             network_resource = {
146                 'vimConnectionId': network.vimid,
147                 'resourceId': network.resouceid,
148                 'resourceProviderId': network.name,
149                 'vimLevelResourceType': 'network'
150             }
151             affected_vls.append({
152                 'id': network.networkid,
153                 'virtualLinkDescId': network.nodeId,
154                 'changeType': 'REMOVED',
155                 'networkResource': network_resource
156             })
157         ext_link_ports = []
158         ports = PortInstModel.objects.filter(instid=self.nf_inst_id)
159         for port in ports:
160             ext_link_ports.append({
161                 'id': port.portid,
162                 'resourceHandle': {
163                     'vimConnectionId': port.vimid,
164                     'resourceId': port.resouceid,
165                     'resourceProviderId': port.name,
166                     'vimLevelResourceType': 'port'
167                 },
168                 'cpInstanceId': port.cpinstanceid
169             })
170         affected_vss = []
171         vss = StorageInstModel.objects.filter(instid=self.nf_inst_id)
172         for vs in vss:
173             affected_vss.append({
174                 'id': vs.storageid,
175                 'virtualStorageDescId': vs.nodeId,
176                 'changeType': 'REMOVED',
177                 'storageResource': {
178                     'vimConnectionId': vs.vimid,
179                     'resourceId': vs.resouceid,
180                     'resourceProviderId': vs.name,
181                     'vimLevelResourceType': 'volume'
182                 }
183             })
184         FlavourInstModel.objects.filter(instid=self.nf_inst_id)
185         SubNetworkInstModel.objects.filter(instid=self.nf_inst_id)
186         self.notify_data = {
187             "notificationType": 'VnfLcmOperationOccurrenceNotification',
188             "notificationStatus": 'RESULT',
189             "vnfInstanceId": self.nf_inst_id,
190             "operation": 'TERMINATE',
191             "vnfLcmOpOccId": self.job_id,
192             'affectedVnfcs': affected_vnfcs,
193             'affectedVirtualLinks': affected_vls,
194             'affectedVirtualStorages': affected_vss,
195             'chengedExtConnectivity': [{
196                 'id': None,  # TODO
197                 'resourceHandle': None,  # TODO
198                 'extLinkPorts': ext_link_ports
199             }]
200         }
201
202         vnfInsts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
203         self.notify_data['vnfmInstId'] = vnfInsts[0].vnfminstid
204         logger.info('Notify request data=%s' % self.notify_data)
205
206     def delete_resource(self):
207         logger.info('Rollback resource begin')
208         adaptor.delete_vim_res(self.inst_resource, self.do_notify_delete)
209         logger.info('Rollback resource complete')
210
211     def do_notify_delete(self, res_type, res_id):
212         logger.error('Deleting [%s] resource, resourceid [%s]' % (res_type, res_id))
213         resource_type = RESOURCE_MAP.keys()[RESOURCE_MAP.values().index(res_type)]
214         resource_table = globals().get(resource_type + 'InstModel')
215         resource_table.objects.filter(instid=self.nf_inst_id, resouceid=res_id).delete()
216
217     def lcm_notify(self):
218         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='NOT_INSTANTIATED', lastuptime=now_time())
219         logger.info('Send notify request to nfvo')
220         resp = notify_lcm_to_nfvo(json.dumps(self.notify_data))
221         logger.info('Lcm notify end, response: %s' % resp)
222
223     def vnf_term_failed_handle(self, error_msg):
224         logger.error('VNF termination failed, detail message: %s' % error_msg)
225         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status='failed', lastuptime=now_time())
226         JobUtil.add_job_status(self.job_id, 255, error_msg)