a4ae4df55bf8987651e342f147854e14265fa66c
[vfc/nfvo/lcm.git] / lcm / ns / biz / ns_terminate.py
1 # Copyright 2016 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 json
15 import logging
16 import threading
17 import time
18 import traceback
19
20 from lcm.jobs.const import JOB_INSTANCE_RESPONSE_ID_URI
21 from lcm.pub.database.models import NSInstModel, VLInstModel, FPInstModel, NfInstModel
22 from lcm.pub.exceptions import NSLCMException
23 from lcm.pub.msapi.nslcm import call_from_ns_cancel_resource
24 from lcm.pub.msapi import sdc_run_catalog
25 from lcm.pub.utils.jobutil import JobUtil
26 from lcm.pub.utils.values import ignore_case_get
27 from lcm.pub.utils import restcall
28 from lcm.ns.enum import OWNER_TYPE
29 from lcm.pub.database.models import PNFInstModel
30 from lcm.ns.biz.ns_lcm_op_occ import NsLcmOpOcc
31 from lcm.jobs.enum import JOB_PROGRESS
32 from lcm.ns.enum import NS_INST_STATUS
33 from lcm.workflows import build_in
34
35 logger = logging.getLogger(__name__)
36
37
38 class TerminateNsService(threading.Thread):
39     def __init__(self, ns_inst_id, job_id, request_data):
40         threading.Thread.__init__(self)
41         self.terminate_type = request_data.get('terminationType', 'GRACEFUL')
42         self.terminate_timeout = request_data.get('gracefulTerminationTimeout', 600)
43         self.job_id = job_id
44         self.ns_inst_id = ns_inst_id
45         self.occ_id = NsLcmOpOcc.create(ns_inst_id, "TERMINATE", "PROCESSING", False, request_data)
46
47     def run(self):
48         try:
49             if not NSInstModel.objects.filter(id=self.ns_inst_id):
50                 JobUtil.add_job_status(self.job_id, JOB_PROGRESS.FINISHED, "Need not terminate.", '')
51                 NsLcmOpOcc.update(self.occ_id, "COMPLETED")
52                 return
53             JobUtil.add_job_status(self.job_id, 10, "Starting terminate...", '')
54             NSInstModel.objects.filter(id=self.ns_inst_id).update(status=NS_INST_STATUS.TERMINATING)
55
56             self.cancel_sfc_list()
57             self.cancel_vnf_list()
58             self.cancel_vl_list()
59             self.cancel_pnf_list()
60
61             self.modify_package_state()
62             NSInstModel.objects.filter(id=self.ns_inst_id).update(status='NOT_INSTANTIATED')
63             JobUtil.add_job_status(self.job_id, JOB_PROGRESS.FINISHED, "ns terminate ends.", '')
64             NsLcmOpOcc.update(self.occ_id, "COMPLETED")
65         except NSLCMException as e:
66             JobUtil.add_job_status(self.job_id, JOB_PROGRESS.ERROR, e.args[0])
67             NsLcmOpOcc.update(self.occ_id, operationState="FAILED", error=e.args[0])
68             build_in.post_deal(self.ns_inst_id, "false")
69         except Exception as e:
70             logger.error(e.args[0])
71             logger.error(traceback.format_exc())
72             JobUtil.add_job_status(self.job_id, JOB_PROGRESS.ERROR, "ns terminate fail.")
73             NsLcmOpOcc.update(self.occ_id, operationState="FAILED", error=e.args[0])
74             build_in.post_deal(self.ns_inst_id, "false")
75
76     def modify_package_state(self):
77         ns_inst = NSInstModel.objects.filter(id=self.ns_inst_id)
78         ns_insts = NSInstModel.objects.filter(nspackage_id=ns_inst[0].nspackage_id)
79         if len(ns_insts) == 1:
80             sdc_run_catalog.modify_nsd_state(ns_inst[0].nspackage_id, 0)
81
82     def cancel_vl_list(self):
83         array_vlinst = VLInstModel.objects.filter(ownertype=OWNER_TYPE.NS, ownerid=self.ns_inst_id)
84         if not array_vlinst:
85             logger.info("[cancel_vl_list] no vlinst attatch to ns_inst_id: %s" % self.ns_inst_id)
86             return
87         step_progress = 20 / len(array_vlinst)
88         cur_progress = 70
89         for vlinst in array_vlinst:
90             delete_result = "failed"
91             cur_progress += step_progress
92             try:
93                 ret = call_from_ns_cancel_resource('vl', vlinst.vlinstanceid)
94                 if ret[0] == 0:
95                     result = json.JSONDecoder().decode(ret[1]).get("result", "")
96                     if str(result) == '0':
97                         delete_result = "success"
98             except Exception as e:
99                 logger.error("[cancel_vl_list] error[%s]!" % e.args[0])
100                 logger.error(traceback.format_exc())
101             job_msg = "Delete vlinst:[%s] %s." % (vlinst.vlinstanceid, delete_result)
102             JobUtil.add_job_status(self.job_id, cur_progress, job_msg)
103
104     def cancel_sfc_list(self):
105         array_sfcinst = FPInstModel.objects.filter(nsinstid=self.ns_inst_id)
106         if not array_sfcinst:
107             logger.info("[cancel_sfc_list] no sfcinst attatch to ns_inst_id: %s" % self.ns_inst_id)
108             return
109         step_progress = 20 / len(array_sfcinst)
110         cur_progress = 30
111         for sfcinst in array_sfcinst:
112             cur_progress += step_progress
113             delete_result = "failed"
114             try:
115                 ret = call_from_ns_cancel_resource('sfc', sfcinst.sfcid)
116                 if ret[0] == 0:
117                     result = json.JSONDecoder().decode(ret[1]).get("result", "")
118                     if str(result) == '0':
119                         delete_result = "success"
120             except Exception as e:
121                 logger.error("[cancel_sfc_list] error[%s]!" % e.args[0])
122                 logger.error(traceback.format_exc())
123             job_msg = "Delete sfcinst:[%s] %s." % (sfcinst.sfcid, delete_result)
124             JobUtil.add_job_status(self.job_id, cur_progress, job_msg)
125
126     def cancel_vnf_list(self):
127         array_vnfinst = NfInstModel.objects.filter(ns_inst_id=self.ns_inst_id)
128         if not array_vnfinst:
129             logger.info("[cancel_vnf_list] no vnfinst attatch to ns_inst_id: %s" % self.ns_inst_id)
130             return
131         step_progress = 10 / len(array_vnfinst)
132         cur_progress = 50
133         vnf_jobs = []
134         for vnfinst in array_vnfinst:
135             cur_progress += step_progress
136             delete_result = "failed"
137             vnf_job_id = ''
138             try:
139                 vnf_job_id = self.delete_vnf(vnfinst.nfinstid)
140                 if vnf_job_id:
141                     delete_result = "deleting"
142             except Exception as e:
143                 logger.error("[cancel_vnf_list] error[%s]!" % e.args[0])
144                 logger.error(traceback.format_exc())
145             job_msg = "Delete vnfinst:[%s] %s." % (vnfinst.nfinstid, delete_result)
146             JobUtil.add_job_status(self.job_id, cur_progress, job_msg)
147             vnf_jobs.append((vnfinst.nfinstid, vnf_job_id))
148         self.wait_delete_vnfs(vnf_jobs, cur_progress, step_progress)
149
150     def wait_delete_vnfs(self, vnf_jobs, cur_progress, step_progress):
151         for vnfinstid, vnfjobid in vnf_jobs:
152             try:
153                 cur_progress += step_progress
154                 if not vnfjobid:
155                     continue
156                 is_job_ok = self.wait_delete_vnf_job_finish(vnfjobid)
157                 msg = "%s to delete VNF(%s)" %\
158                       ("Succeed" if is_job_ok else "Failed", vnfinstid)
159                 logger.debug(msg)
160                 JobUtil.add_job_status(self.job_id, cur_progress, msg)
161             except Exception as e:
162                 msg = "Exception occurs(%s) when delete VNF(%s)" % (e, vnfinstid)
163                 logger.debug(msg)
164                 JobUtil.add_job_status(self.job_id, cur_progress, msg)
165
166     def delete_vnf(self, nf_instid):
167         term_param = {
168             "terminationType": self.terminate_type
169         }
170         if self.terminate_timeout:
171             term_param["gracefulTerminationTimeout"] = int(self.terminate_timeout)
172         ret = call_from_ns_cancel_resource('vnf', nf_instid, term_param)
173         if ret[0] != 0:
174             logger.error("Terminate VNF(%s) failed: %s", nf_instid, ret[1])
175             return ''
176         job_info = json.JSONDecoder().decode(ret[1])
177         vnf_job_id = ignore_case_get(job_info, "jobId")
178         return vnf_job_id
179
180     def wait_delete_vnf_job_finish(self, vnf_job_id):
181         count = 0
182         retry_count = 400
183         interval_second = 2
184         response_id, new_response_id = 0, 0
185         job_end_normal, job_timeout = False, True
186         while count < retry_count:
187             count = count + 1
188             time.sleep(interval_second)
189             uri = JOB_INSTANCE_RESPONSE_ID_URI % (vnf_job_id, response_id)
190             ret = restcall.req_by_msb(uri, "GET")
191             if ret[0] != 0:
192                 logger.error("Failed to query job: %s:%s", ret[2], ret[1])
193                 continue
194             job_result = json.JSONDecoder().decode(ret[1])
195             if "responseDescriptor" not in job_result:
196                 logger.debug("No new progress after response_id(%s) in job(%s)", response_id, vnf_job_id)
197                 continue
198             progress = job_result["responseDescriptor"]["progress"]
199             new_response_id = job_result["responseDescriptor"]["responseId"]
200             job_desc = job_result["responseDescriptor"]["statusDescription"]
201             if new_response_id != response_id:
202                 logger.debug("%s:%s:%s", progress, new_response_id, job_desc)
203                 response_id = new_response_id
204                 count = 0
205             if progress == JOB_PROGRESS.ERROR:
206                 job_timeout = False
207                 logger.error("Job(%s) failed: %s", vnf_job_id, job_desc)
208                 break
209             elif progress == JOB_PROGRESS.FINISHED:
210                 job_end_normal, job_timeout = True, False
211                 logger.info("Job(%s) ended normally", vnf_job_id)
212                 break
213         if job_timeout:
214             logger.error("Job(%s) timeout", vnf_job_id)
215         return job_end_normal
216
217     def cancel_pnf_list(self):
218         pnfinst_list = PNFInstModel.objects.filter(nsInstances__contains=self.ns_inst_id)
219         if len(pnfinst_list) > 0:
220             cur_progress = 90
221             step_progress = 5 / len(pnfinst_list)
222             for pnfinst in pnfinst_list:
223                 delete_result = "fail"
224                 try:
225                     ret = call_from_ns_cancel_resource('pnf', pnfinst.pnfId)
226                     if ret[0] == 0:
227                         delete_result = "success"
228                 except Exception as e:
229                     logger.error("[cancel_pnf_list] error[%s]!" % e.args[0])
230                     logger.error(traceback.format_exc())
231                 job_msg = "Delete pnfinst:[%s] %s" % (pnfinst.pnfId, delete_result)
232                 cur_progress += step_progress
233                 JobUtil.add_job_status(self.job_id, cur_progress, job_msg)