add comments
[vfc/nfvo/lcm.git] / lcm / ns / biz / ns_update.py
1 # Copyright (c) 2018, CMCC Technologies Co., Ltd.
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 logging
15 import threading
16 import traceback
17 import datetime
18 import time
19
20 from lcm.ns.enum import NS_INST_STATUS, OPERATIONAL_STATE, STOP_TYPE
21 from lcm.pub.database.models import JobModel, NSInstModel
22 from lcm.ns_vnfs.biz.update_vnfs import NFOperateService
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.biz.ns_lcm_op_occ import NsLcmOpOcc
28
29 logger = logging.getLogger(__name__)
30
31
32 class NSUpdateService(threading.Thread):
33     """
34     Update NS instance model
35     """
36
37     def __init__(self, ns_instance_id, request_data, job_id):
38         super(NSUpdateService, self).__init__()
39         self.ns_instance_id = ns_instance_id
40         self.request_data = request_data
41         self.job_id = job_id
42         self.occ_id = NsLcmOpOcc.create(ns_instance_id, "SCALE", "PROCESSING", False, request_data)
43         self.update_type = ''
44         self.operate_vnf_data = ''
45
46     def run(self):
47         try:
48             self.do_biz()
49         except NSLCMException as e:
50             logger.error(traceback.format_exc())
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 update fail')
56             NsLcmOpOcc.update(self.occ_id, operationState="FAILED", error=e.args[0])
57
58     def do_biz(self):
59         self.update_job(JOB_PROGRESS.STARTED, desc='ns update start')
60         self.get_and_check_params()
61         self.update_ns_status(NS_INST_STATUS.UPDATING)
62         self.do_update()
63         self.update_ns_status(NS_INST_STATUS.ACTIVE)
64         self.update_job(JOB_PROGRESS.FINISHED, desc='ns update 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             raise NSLCMException(
71                 'NS [id=%s] does not exist' % self.ns_instance_id)
72
73         self.update_type = ignore_case_get(self.request_data, "updateType")
74         if not self.update_type:
75             raise NSLCMException(
76                 'UpdateType parameter does not exist or value incorrect.')
77
78     def do_update(self):
79         if self.update_type == "OPERATE_VNF":
80             self.operate_vnf_data = ignore_case_get(
81                 self.request_data, "operateVnfData")
82             if not self.operate_vnf_data:
83                 raise NSLCMException(
84                     'OperateVnfData does not exist or value is incorrect.')
85             for vnf_update_data in self.operate_vnf_data:
86                 vnf_update_params = self.prepare_update_params(vnf_update_data)
87                 status = self.do_vnf_update(vnf_update_params, 15)
88                 if status is JOB_MODEL_STATUS.FINISHED:
89                     logger.info(
90                         'nf[%s] update handle end' % vnf_update_params.get('vnfInstanceId'))
91                     self.update_job(90,
92                                     desc='nf[%s] update handle end'
93                                          % vnf_update_params.get('vnfInstanceId'))
94                 else:
95                     raise NSLCMException('nf update failed')
96         else:
97             raise NSLCMException('Method update.')
98
99     def do_vnf_update(self, vnf_update_params, progress):
100         vnf_instance_id = vnf_update_params.get('vnfInstanceId')
101         nf_service = NFOperateService(vnf_instance_id, vnf_update_params)
102         nf_service.start()
103         self.update_job(progress, desc='nf[%s] update handle start' % vnf_instance_id)
104         status = self.wait_job_finish(nf_service.job_id)
105         return status
106
107     @staticmethod
108     def prepare_update_params(vnf_data):
109         vnf_instance_id = ignore_case_get(vnf_data, 'vnfInstanceId')
110         if not vnf_instance_id:
111             raise NSLCMException(
112                 'VnfInstanceId does not exist or value is incorrect.')
113
114         change_state_to = ignore_case_get(vnf_data, 'changeStateTo')
115         if not change_state_to:
116             raise NSLCMException(
117                 'ChangeStateTo does not exist or value is incorrect.')
118         graceful_stop_timeout = ''
119         operational_states = ignore_case_get(change_state_to, 'OperationalStates')
120         if operational_states == OPERATIONAL_STATE.STOPPED:
121             stop_type = ignore_case_get(vnf_data, 'stopType')
122             if stop_type == STOP_TYPE.GRACEFUL:
123                 graceful_stop_timeout = ignore_case_get(vnf_data, 'gracefulStopTimeout')
124
125         result = {
126             "vnfInstanceId": vnf_instance_id,
127             "changeStateTo": operational_states,
128             "stopType": stop_type,
129             "gracefulStopTimeout": graceful_stop_timeout if graceful_stop_timeout else 0
130         }
131         return result
132
133     @staticmethod
134     def wait_job_finish(sub_job_id, timeout=3600):
135         query_interval = 2
136         start_time = end_time = datetime.datetime.now()
137         while (end_time - start_time).seconds < timeout:
138             job_result = JobModel.objects.get(jobid=sub_job_id)
139             time.sleep(query_interval)
140             end_time = datetime.datetime.now()
141             if job_result.progress == JOB_PROGRESS.FINISHED:
142                 return JOB_MODEL_STATUS.FINISHED
143             elif job_result.progress > JOB_PROGRESS.FINISHED:
144                 return JOB_MODEL_STATUS.ERROR
145             else:
146                 continue
147         return JOB_MODEL_STATUS.TIMEOUT
148
149     def update_job(self, progress, desc=''):
150         JobUtil.add_job_status(self.job_id, progress, desc)
151
152     def update_ns_status(self, status):
153         NSInstModel.objects.filter(id=self.ns_instance_id).update(status=status)