add comments
[vfc/nfvo/lcm.git] / lcm / ns / biz / ns_heal.py
1 # Copyright 2017 Intel 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 datetime
16 import logging
17 import threading
18 import time
19 import traceback
20
21 from lcm.ns.enum import NS_INST_STATUS
22 from lcm.pub.database.models import JobModel, NSInstModel, NfInstModel, VNFCInstModel, VmInstModel
23 from lcm.pub.exceptions import NSLCMException
24 from lcm.pub.utils.jobutil import JobUtil
25 from lcm.jobs.enum import JOB_MODEL_STATUS, JOB_PROGRESS
26 from lcm.pub.utils.values import ignore_case_get
27 from lcm.ns_vnfs.biz.heal_vnfs import NFHealService
28 from lcm.ns.biz.ns_lcm_op_occ import NsLcmOpOcc
29
30 logger = logging.getLogger(__name__)
31
32
33 class NSHealService(threading.Thread):
34     """
35     Heal the NS instance
36     """
37
38     def __init__(self, ns_instance_id, request_data, job_id):
39         super(NSHealService, self).__init__()
40         self.ns_instance_id = ns_instance_id
41         self.request_data = request_data
42         self.job_id = job_id
43         self.occ_id = NsLcmOpOcc.create(ns_instance_id, "HEAL", "PROCESSING", False, request_data)
44         self.heal_vnf_data = ''
45         self.heal_ns_data = ''
46
47     def run(self):
48         try:
49             self.do_biz()
50         except NSLCMException as e:
51             JobUtil.add_job_status(self.job_id, JOB_PROGRESS.ERROR, e.args[0])
52             NsLcmOpOcc.update(self.occ_id, operationState="FAILED", error=e.args[0])
53         except Exception as e:
54             logger.error(traceback.format_exc())
55             JobUtil.add_job_status(self.job_id, JOB_PROGRESS.ERROR, 'ns heal fail')
56             NsLcmOpOcc.update(self.occ_id, operationState="FAILED", error=e.args[0])
57
58     def do_biz(self):
59         self.update_job(1, desc='ns heal start')
60         self.get_and_check_params()
61         self.update_ns_status(NS_INST_STATUS.HEALING)
62         self.do_heal()
63         self.update_ns_status(NS_INST_STATUS.ACTIVE)
64         self.update_job(100, desc='ns heal success')
65         NsLcmOpOcc.update(self.occ_id, "COMPLETED")
66
67     def get_and_check_params(self):
68         ns_info = NSInstModel.objects.filter(id=self.ns_instance_id)
69         if not ns_info:
70             errmsg = 'NS [id=%s] does not exist' % self.ns_instance_id
71             raise NSLCMException(errmsg)
72
73         self.heal_ns_data = ignore_case_get(self.request_data, 'healNsData')
74         self.heal_vnf_data = ignore_case_get(self.request_data, 'healVnfData')
75
76         if self.heal_ns_data and self.heal_vnf_data:
77             errmsg = 'healNsData and healVnfData can not exist together'
78             logger.error(errmsg)
79             raise NSLCMException(errmsg)
80
81         if not self.heal_ns_data and not self.heal_vnf_data:
82             errmsg = 'healNsData and healVnfData parameters does not exist or value is incorrect.'
83             raise NSLCMException(errmsg)
84
85     def do_heal(self):
86         if self.heal_vnf_data:
87             vnf_heal_params = self.prepare_vnf_heal_params(self.heal_vnf_data)
88             status = self.do_vnf_or_ns_heal(vnf_heal_params, 15)
89             if status is JOB_MODEL_STATUS.FINISHED:
90                 logger.info('nf[%s] heal handle end' % vnf_heal_params.get('vnfInstanceId'))
91                 self.update_job(90, desc='nf[%s] heal handle end' % vnf_heal_params.get('vnfInstanceId'))
92             else:
93                 errmsg = 'nf heal failed'
94                 raise NSLCMException(errmsg)
95         else:
96             ns_heal_params = self.prepare_ns_heal_params(self.heal_ns_data)
97             for ns_heal_param in ns_heal_params:
98                 status = self.do_vnf_or_ns_heal(ns_heal_param, 15)
99                 if status is JOB_MODEL_STATUS.FINISHED:
100                     logger.info('nf[%s] heal handle end' % ns_heal_param.get('vnfInstanceId'))
101                     self.update_job(90, desc='nf[%s] heal handle end' % ns_heal_param.get('vnfInstanceId'))
102                 else:
103                     errmsg = 'nf heal failed'
104                     logger.error(errmsg)
105                     raise NSLCMException(errmsg)
106
107     def do_vnf_or_ns_heal(self, heal_param, progress):
108         instance_id = heal_param.get('vnfInstanceId')
109         nf_service = NFHealService(instance_id, heal_param)
110         nf_service.start()
111         self.update_job(
112             progress, desc='nf[%s] heal handle start' % instance_id)
113         status = self.wait_job_finish(nf_service.job_id)
114         return status
115
116     def prepare_ns_heal_params(self, ns_data):
117         degree_healing = ignore_case_get(ns_data, 'degreeHealing')
118         if not degree_healing:
119             errmsg = 'degreeHealing does not exist.'
120             logger.error(errmsg)
121             raise NSLCMException(errmsg)
122         ns_instance_id = self.ns_instance_id
123         cause = 'vm is down'
124         # action = ignore_case_get(ns_data, 'actionsHealing')
125         if degree_healing == "HEAL_RESTORE":
126             ns_inst_infos = NfInstModel.objects.filter(ns_inst_id=self.ns_instance_id)
127             if not ns_inst_infos.exists():
128                 raise NSLCMException('NSInsts(%s) does not exist' % self.ns_instance_id)
129             result_arr = []
130             for ns_inst_info in ns_inst_infos:
131                 vnfc_insts = VNFCInstModel.objects.filter(nfinstid=ns_inst_info.nfinstid)
132                 # If a condition is not met, will it all terminate?
133                 if not vnfc_insts.exists():
134                     raise NSLCMException('vnfcinsts(%s) does not exist' % ns_inst_info.nfinstid)
135                 for vnfc_inst in vnfc_insts:
136                     vm_id = vnfc_inst.vmid
137                     vdu_id = vnfc_inst.vduid
138                     vm_inst_info = VmInstModel.objects.filter(vmid=vm_id)
139                     if not vm_inst_info.exists():
140                         raise NSLCMException('vminstinfo(%s) does not exist' % vm_id)
141                     vm_name = vm_inst_info[0].vmname
142
143                     result = {
144                         "vnfInstanceId": ns_instance_id,
145                         "cause": cause,
146                         "additionalParams": {
147                             "action": "restartvm",
148                             "actionvminfo": {
149                                 "vmid": vm_id,
150                                 "vduid": vdu_id,
151                                 "vmname": vm_name
152                             }
153                         }
154                     }
155                     result_arr.append(result)
156             return result_arr
157         else:
158             errmsg = 'The degree of healing dose not exist or value is incorrect.'
159             logger.error(errmsg)
160             raise NSLCMException(errmsg)
161
162     def prepare_vnf_heal_params(self, vnf_data):
163         vnf_instance_id = ignore_case_get(vnf_data, 'vnfInstanceId')
164         if not vnf_instance_id:
165             errmsg = 'vnfinstanceid does not exist or value is incorrect.'
166             logger.error(errmsg)
167             raise NSLCMException(errmsg)
168         cause = ignore_case_get(vnf_data, 'cause')
169         additional_params = ignore_case_get(vnf_data, 'additionalParams')
170         action = ignore_case_get(additional_params, 'action')
171         action_vm_info = ignore_case_get(additional_params, 'actionvminfo')
172         vm_id = ignore_case_get(action_vm_info, 'vmid')
173         vdu_id = ignore_case_get(action_vm_info, 'vduid')
174         vm_name = ignore_case_get(action_vm_info, 'vmname')
175
176         result = {
177             "vnfInstanceId": vnf_instance_id,
178             "cause": cause,
179             "additionalParams": {
180                 "action": action,
181                 "actionvminfo": {
182                     "vmid": vm_id,
183                     "vduid": vdu_id,
184                     "vmname": vm_name
185                 }
186             }
187         }
188         return result
189
190     @staticmethod
191     def wait_job_finish(sub_job_id, timeout=3600):
192         query_interval = 2
193         start_time = end_time = datetime.datetime.now()
194         while (end_time - start_time).seconds < timeout:
195             job_result = JobModel.objects.get(jobid=sub_job_id)
196             time.sleep(query_interval)
197             end_time = datetime.datetime.now()
198             if job_result.progress == JOB_PROGRESS.FINISHED:
199                 return JOB_MODEL_STATUS.FINISHED
200             elif job_result.progress > JOB_PROGRESS.FINISHED:
201                 return JOB_MODEL_STATUS.ERROR
202             else:
203                 continue
204         return JOB_MODEL_STATUS.TIMEOUT
205
206     def update_job(self, progress, desc=''):
207         JobUtil.add_job_status(self.job_id, progress, desc)
208
209     def update_ns_status(self, status):
210         NSInstModel.objects.filter(
211             id=self.ns_instance_id).update(status=status)