1 # Copyright 2016 ZTE Corporation.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
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
34 logger = logging.getLogger(__name__)
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)
43 self.ns_inst_id = ns_inst_id
44 self.occ_id = NsLcmOpOcc.create(ns_inst_id, "TERMINATE", "PROCESSING", False, request_data)
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")
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)
55 self.cancel_sfc_list()
56 self.cancel_vnf_list()
58 self.cancel_pnf_list()
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")
74 def cancel_vl_list(self):
75 array_vlinst = VLInstModel.objects.filter(ownertype=OWNER_TYPE.NS, ownerid=self.ns_inst_id)
77 logger.info("[cancel_vl_list] no vlinst attatch to ns_inst_id: %s" % self.ns_inst_id)
79 step_progress = 20 / len(array_vlinst)
81 for vlinst in array_vlinst:
82 delete_result = "failed"
83 cur_progress += step_progress
85 ret = call_from_ns_cancel_resource('vl', vlinst.vlinstanceid)
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)
96 def cancel_sfc_list(self):
97 array_sfcinst = FPInstModel.objects.filter(nsinstid=self.ns_inst_id)
99 logger.info("[cancel_sfc_list] no sfcinst attatch to ns_inst_id: %s" % self.ns_inst_id)
101 step_progress = 20 / len(array_sfcinst)
103 for sfcinst in array_sfcinst:
104 cur_progress += step_progress
105 delete_result = "failed"
107 ret = call_from_ns_cancel_resource('sfc', sfcinst.sfcid)
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)
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)
123 step_progress = 10 / len(array_vnfinst)
126 for vnfinst in array_vnfinst:
127 cur_progress += step_progress
128 delete_result = "failed"
131 vnf_job_id = self.delete_vnf(vnfinst.nfinstid)
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))
141 thread = threading.Thread(
142 target=self.wait_delete_vnfs,
143 args=(vnf_jobs, cur_progress, step_progress,))
146 def wait_delete_vnfs(self, vnf_jobs, cur_progress, step_progress):
147 for vnfinstid, vnfjobid in vnf_jobs:
149 cur_progress += step_progress
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)
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)
160 JobUtil.add_job_status(self.job_id, cur_progress, msg)
162 def delete_vnf(self, nf_instid):
164 "terminationType": self.terminate_type
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)
170 logger.error("Terminate VNF(%s) failed: %s", nf_instid, ret[1])
172 job_info = json.JSONDecoder().decode(ret[1])
173 vnf_job_id = ignore_case_get(job_info, "jobId")
176 def wait_delete_vnf_job_finish(self, vnf_job_id):
180 response_id, new_response_id = 0, 0
181 job_end_normal, job_timeout = False, True
182 while count < retry_count:
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")
188 logger.error("Failed to query job: %s:%s", ret[2], ret[1])
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)
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
201 if progress == JOB_PROGRESS.ERROR:
203 logger.error("Job(%s) failed: %s", vnf_job_id, job_desc)
205 elif progress == JOB_PROGRESS.FINISHED:
206 job_end_normal, job_timeout = True, False
207 logger.info("Job(%s) ended normally", vnf_job_id)
210 logger.error("Job(%s) timeout", vnf_job_id)
211 return job_end_normal
213 def cancel_pnf_list(self):
214 pnfinst_list = PNFInstModel.objects.filter(nsInstances__contains=self.ns_inst_id)
215 if len(pnfinst_list) > 0:
217 step_progress = 5 / len(pnfinst_list)
218 for pnfinst in pnfinst_list:
219 delete_result = "fail"
221 ret = call_from_ns_cancel_resource('pnf', pnfinst.pnfId)
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)