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