Merge "Add additional unit tests and asserts for NS Heal."
[vfc/nfvo/lcm.git] / lcm / ns / 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 logging
16 import threading
17 import traceback
18 import datetime
19 import time
20
21 from lcm.ns.const import NS_INST_STATUS
22 from lcm.pub.database.models import JobModel, NSInstModel, NfInstModel
23 from lcm.ns.vnfs.heal_vnfs import NFHealService
24 from lcm.pub.exceptions import NSLCMException
25 from lcm.pub.utils.jobutil import JobUtil, JOB_MODEL_STATUS
26 from lcm.pub.utils.values import ignore_case_get
27
28 JOB_ERROR = 255
29 logger = logging.getLogger(__name__)
30
31
32 class NSHealService(threading.Thread):
33     def __init__(self, ns_instance_id, request_data, job_id):
34         super(NSHealService, self).__init__()
35         self.ns_instance_id = ns_instance_id
36         self.request_data = request_data
37         self.job_id = job_id
38
39         self.heal_vnf_data = ''
40
41     def run(self):
42         try:
43             self.do_biz()
44         except NSLCMException as e:
45             JobUtil.add_job_status(self.job_id, JOB_ERROR, e.message)
46         except:
47             logger.error(traceback.format_exc())
48             JobUtil.add_job_status(self.job_id, JOB_ERROR, 'ns heal fail')
49
50     def do_biz(self):
51         self.update_job(1, desc='ns heal start')
52         self.get_and_check_params()
53         self.update_ns_status(NS_INST_STATUS.HEALING)
54         self.do_vnfs_heal()
55         self.update_ns_status(NS_INST_STATUS.ACTIVE)
56         self.update_job(100, desc='ns heal success')
57
58     def get_and_check_params(self):
59         ns_info = NSInstModel.objects.filter(id=self.ns_instance_id)
60         if not ns_info:
61             logger.error('NS [id=%s] does not exist' % self.ns_instance_id)
62             raise NSLCMException('NS [id=%s] does not exist' % self.ns_instance_id)
63         self.heal_vnf_data = ignore_case_get(self.request_data, 'healVnfData')
64         if not self.heal_vnf_data:
65             logger.error('healVnfData parameter does not exist or value is incorrect.')
66             raise NSLCMException('healVnfData parameter does not exist or value incorrect.')
67
68     def do_vnfs_heal(self):
69         vnf_heal_params = self.prepare_vnf_heal_params(self.heal_vnf_data)
70         count = len(self.heal_vnf_data)
71         # TODO(sshank): Check progress_range
72         progress_range = [11 + 80 / count, 10 + 80 / count]
73         status = self.do_vnf_heal(vnf_heal_params, progress_range)
74         if status is JOB_MODEL_STATUS.FINISHED:
75             logger.info('nf[%s] heal handle end' % vnf_heal_params.get('vnfInstanceId'))
76             self.update_job(progress_range[1],
77                             desc='nf[%s] heal handle end' % vnf_heal_params.get('vnfInstanceId'))
78         else:
79             logger.error('nf heal failed')
80             raise NSLCMException('nf heal failed')
81
82     def do_vnf_heal(self, vnf_heal_params, progress_range):
83         vnf_instance_id = vnf_heal_params.get('vnfInstanceId')
84         nf_service = NFHealService(vnf_instance_id, vnf_heal_params)
85         nf_service.start()
86         self.update_job(progress_range[0], desc='nf[%s] heal handle start' % vnf_instance_id)
87         status = self.wait_job_finish(nf_service.job_id)
88         return status
89
90     def prepare_vnf_heal_params(self, vnf_data):
91         vnf_instance_id = ignore_case_get(vnf_data, 'vnfInstanceId')
92         cause = ignore_case_get(vnf_data, "cause")
93         additional_params = ignore_case_get(vnf_data, "additionalParams")
94         result = {
95             "vnfInstanceId": vnf_instance_id,
96             "cause": cause,
97             "additionalParams": additional_params
98         }
99         return result
100
101     @staticmethod
102     def wait_job_finish(sub_job_id, timeout=3600):
103         query_interval = 2
104         start_time = end_time = datetime.datetime.now()
105         while (end_time - start_time).seconds < timeout:
106             job_result = JobModel.objects.get(jobid=sub_job_id)
107             time.sleep(query_interval)
108             end_time = datetime.datetime.now()
109             if job_result.progress == 100:
110                 return JOB_MODEL_STATUS.FINISHED
111             elif job_result.progress > 100:
112                 return JOB_MODEL_STATUS.ERROR
113             else:
114                 continue
115         return JOB_MODEL_STATUS.TIMEOUT
116
117     def update_job(self, progress, desc=''):
118         JobUtil.add_job_status(self.job_id, progress, desc)
119
120     def update_ns_status(self, status):
121         NSInstModel.objects.filter(id=self.ns_instance_id).update(status=status)