Add lcm op occ to term vnf
[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
28 from lcm.pub.msapi.gvnfmdriver import notify_lcm_to_nfvo
29 from lcm.pub.utils.jobutil import JobUtil
30 from lcm.pub.utils.timeutil import now_time
31 from lcm.pub.utils.notificationsutil import NotificationsUtil
32 from lcm.pub.utils.values import ignore_case_get
33 from lcm.pub.vimapi import adaptor
34 from lcm.nf.biz.grant_vnf import grant_resource
35 from lcm.nf.const import CHANGE_TYPE, GRANT_TYPE, OPERATION_TYPE
36 from lcm.nf.const import OPERATION_TASK
37 from lcm.nf.const import OPERATION_STATE_TYPE
38 from .operate_vnf_lcm_op_occ import VnfLcmOpOcc
39
40 logger = logging.getLogger(__name__)
41
42
43 class TerminateVnf(Thread):
44     def __init__(self, data, nf_inst_id, job_id):
45         super(TerminateVnf, self).__init__()
46         self.data = data
47         self.nf_inst_id = nf_inst_id
48         self.job_id = job_id
49         self.terminationType = ignore_case_get(
50             self.data,
51             "terminationType"
52         )
53         self.gracefulTerminationTimeout = ignore_case_get(
54             self.data,
55             "gracefulTerminationTimeout"
56         )
57         self.inst_resource = {
58             'volumn': [],
59             'network': [],
60             'subnet': [],
61             'port': [],
62             'flavor': [],
63             'vm': []
64         }
65         self.grant_type = GRANT_TYPE.TERMINATE
66         self.lcm_op_occ = VnfLcmOpOcc(
67             vnf_inst_id=nf_inst_id,
68             lcm_op_id=job_id,
69             operation=OPERATION_TYPE.SCALE,
70             task=OPERATION_TASK.SCALE
71         )
72
73     def run(self):
74         try:
75             if self.term_pre():
76                 vdus = VmInstModel.objects.filter(
77                     instid=self.nf_inst_id,
78                     is_predefined=1
79                 )
80                 self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.STARTING)
81                 apply_result = grant_resource(
82                     data=self.data,
83                     nf_inst_id=self.nf_inst_id,
84                     job_id=self.job_id,
85                     grant_type=self.grant_type,
86                     vdus=vdus
87                 )
88                 self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.PROCESSING)
89                 logger.info("Grant resource end, response: %s" % apply_result)
90                 JobUtil.add_job_status(
91                     self.job_id,
92                     20,
93                     'Nf terminating grant_resource finish'
94                 )
95                 self.query_inst_resource()
96                 self.query_notify_data()
97                 self.delete_resource()
98                 self.lcm_notify()
99             JobUtil.add_job_status(
100                 self.job_id,
101                 100,
102                 "Terminate Vnf success."
103             )
104         except NFLCMException as e:
105             self.vnf_term_failed_handle(e.message)
106         except Exception as e:
107             logger.error(e.message)
108             logger.error(traceback.format_exc())
109             self.vnf_term_failed_handle(e.message)
110
111     def term_pre(self):
112         vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
113         if not vnf_insts.exists():
114             logger.warn('VnfInst(%s) does not exist' % self.nf_inst_id)
115             return False
116         if self.terminationType == 'GRACEFUL' and not self.gracefulTerminationTimeout:
117             logger.warn("Set Graceful default termination timeout = 60")
118             self.gracefulTerminationTimeout = 60
119         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.TERMINATING)
120         JobUtil.add_job_status(self.job_id, 10, 'Nf terminating pre-check finish')
121         logger.info("Nf terminating pre-check finish")
122         return True
123
124     def query_inst_resource(self):
125         logger.info('Query resource begin')
126         for resource_type in RESOURCE_MAP.keys():
127             resource_table = globals().get(resource_type + 'InstModel')
128             resource_insts = resource_table.objects.filter(instid=self.nf_inst_id)
129             for resource_inst in resource_insts:
130                 if not resource_inst.resourceid:
131                     continue
132                 self.inst_resource[RESOURCE_MAP.get(resource_type)].append(self.get_resource(resource_inst))
133         logger.info('Query resource end, resource=%s' % self.inst_resource)
134
135     def get_resource(self, resource):
136         return {
137             "vim_id": resource.vimid,
138             "tenant_id": resource.tenant,
139             "res_id": resource.resourceid,
140             "is_predefined": resource.is_predefined
141         }
142
143     def query_notify_data(self):
144         self.notify_data = prepare_notification_data(
145             self.nf_inst_id,
146             self.job_id,
147             CHANGE_TYPE.REMOVED,
148             OPERATION_TYPE.TERMINATE
149         )
150         NetworkInstModel.objects.filter(instid=self.nf_inst_id)
151         StorageInstModel.objects.filter(instid=self.nf_inst_id)
152         PortInstModel.objects.filter(instid=self.nf_inst_id)
153         VNFCInstModel.objects.filter(instid=self.nf_inst_id)
154         FlavourInstModel.objects.filter(instid=self.nf_inst_id)
155         SubNetworkInstModel.objects.filter(instid=self.nf_inst_id)
156
157     def delete_resource(self):
158         logger.info('Rollback resource begin')
159         adaptor.delete_vim_res(
160             self.inst_resource,
161             self.do_notify_delete
162         )
163         logger.info('Rollback resource complete')
164
165     def do_notify_delete(self, res_type, res_id):
166         logger.debug('Deleting [%s] resource, resourceid [%s]' % (res_type, res_id))
167         resource_type = RESOURCE_MAP.keys()[RESOURCE_MAP.values().index(res_type)]
168         resource_table = globals().get(resource_type + 'InstModel')
169         resource_table.objects.filter(instid=self.nf_inst_id, resourceid=res_id).delete()
170
171     def lcm_notify(self):
172         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(
173             status='NOT_INSTANTIATED',
174             lastuptime=now_time()
175         )
176         logger.info('Send notify request to nfvo')
177         try:
178             resp = notify_lcm_to_nfvo(json.dumps(self.notify_data))
179             logger.info('Lcm notify end, response: %s' % resp)
180             NotificationsUtil().send_notification(self.notify_data)
181         except Exception as e:
182             logger.error("Lcm terminate notify failed: %s", e.message)
183
184     def vnf_term_failed_handle(self, error_msg):
185         logger.error('VNF termination failed, detail message: %s' % error_msg)
186         NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(lastuptime=now_time())
187         self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.FAILED, error_msg)
188         JobUtil.add_job_status(self.job_id, 255, error_msg)