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