Automation adds vfc-nfvo-lcm-architecture.rst
[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
149         thread = threading.Thread(
150             target=self.wait_delete_vnfs,
151             args=(vnf_jobs, cur_progress, step_progress,))
152         thread.start()
153
154     def wait_delete_vnfs(self, vnf_jobs, cur_progress, step_progress):
155         for vnfinstid, vnfjobid in vnf_jobs:
156             try:
157                 cur_progress += step_progress
158                 if not vnfjobid:
159                     continue
160                 is_job_ok = self.wait_delete_vnf_job_finish(vnfjobid)
161                 msg = "%s to delete VNF(%s)" %\
162                       ("Succeed" if is_job_ok else "Failed", vnfinstid)
163                 logger.debug(msg)
164                 JobUtil.add_job_status(self.job_id, cur_progress, msg)
165             except Exception as e:
166                 msg = "Exception occurs(%s) when delete VNF(%s)" % (e, vnfinstid)
167                 logger.debug(msg)
168                 JobUtil.add_job_status(self.job_id, cur_progress, msg)
169
170     def delete_vnf(self, nf_instid):
171         term_param = {
172             "terminationType": self.terminate_type
173         }
174         if self.terminate_timeout:
175             term_param["gracefulTerminationTimeout"] = int(self.terminate_timeout)
176         ret = call_from_ns_cancel_resource('vnf', nf_instid, term_param)
177         if ret[0] != 0:
178             logger.error("Terminate VNF(%s) failed: %s", nf_instid, ret[1])
179             return ''
180         job_info = json.JSONDecoder().decode(ret[1])
181         vnf_job_id = ignore_case_get(job_info, "jobId")
182         return vnf_job_id
183
184     def wait_delete_vnf_job_finish(self, vnf_job_id):
185         count = 0
186         retry_count = 400
187         interval_second = 2
188         response_id, new_response_id = 0, 0
189         job_end_normal, job_timeout = False, True
190         while count < retry_count:
191             count = count + 1
192             time.sleep(interval_second)
193             uri = JOB_INSTANCE_RESPONSE_ID_URI % (vnf_job_id, response_id)
194             ret = restcall.req_by_msb(uri, "GET")
195             if ret[0] != 0:
196                 logger.error("Failed to query job: %s:%s", ret[2], ret[1])
197                 continue
198             job_result = json.JSONDecoder().decode(ret[1])
199             if "responseDescriptor" not in job_result:
200                 logger.debug("No new progress after response_id(%s) in job(%s)", response_id, vnf_job_id)
201                 continue
202             progress = job_result["responseDescriptor"]["progress"]
203             new_response_id = job_result["responseDescriptor"]["responseId"]
204             job_desc = job_result["responseDescriptor"]["statusDescription"]
205             if new_response_id != response_id:
206                 logger.debug("%s:%s:%s", progress, new_response_id, job_desc)
207                 response_id = new_response_id
208                 count = 0
209             if progress == JOB_PROGRESS.ERROR:
210                 job_timeout = False
211                 logger.error("Job(%s) failed: %s", vnf_job_id, job_desc)
212                 break
213             elif progress == JOB_PROGRESS.FINISHED:
214                 job_end_normal, job_timeout = True, False
215                 logger.info("Job(%s) ended normally", vnf_job_id)
216                 break
217         if job_timeout:
218             logger.error("Job(%s) timeout", vnf_job_id)
219         return job_end_normal
220
221     def cancel_pnf_list(self):
222         pnfinst_list = PNFInstModel.objects.filter(nsInstances__contains=self.ns_inst_id)
223         if len(pnfinst_list) > 0:
224             cur_progress = 90
225             step_progress = 5 / len(pnfinst_list)
226             for pnfinst in pnfinst_list:
227                 delete_result = "fail"
228                 try:
229                     ret = call_from_ns_cancel_resource('pnf', pnfinst.pnfId)
230                     if ret[0] == 0:
231                         delete_result = "success"
232                 except Exception as e:
233                     logger.error("[cancel_pnf_list] error[%s]!" % e.args[0])
234                     logger.error(traceback.format_exc())
235                 job_msg = "Delete pnfinst:[%s] %s" % (pnfinst.pnfId, delete_result)
236                 cur_progress += step_progress
237                 JobUtil.add_job_status(self.job_id, cur_progress, job_msg)