6d996d2934ae582b11337b705cab84fd3005236f
[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     def __init__(self, ns_instance_id, request_data, job_id):
34         super(NSUpdateService, self).__init__()
35         self.ns_instance_id = ns_instance_id
36         self.request_data = request_data
37         self.job_id = job_id
38         self.occ_id = NsLcmOpOcc.create(ns_instance_id, "SCALE", "PROCESSING", False, request_data)
39         self.update_type = ''
40         self.operate_vnf_data = ''
41
42     def run(self):
43         try:
44             self.do_biz()
45         except NSLCMException as e:
46             logger.error(traceback.format_exc())
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 update fail')
52             NsLcmOpOcc.update(self.occ_id, operationState="FAILED", error=e.args[0])
53
54     def do_biz(self):
55         self.update_job(JOB_PROGRESS.STARTED, desc='ns update start')
56         self.get_and_check_params()
57         self.update_ns_status(NS_INST_STATUS.UPDATING)
58         self.do_update()
59         self.update_ns_status(NS_INST_STATUS.ACTIVE)
60         self.update_job(JOB_PROGRESS.FINISHED, desc='ns update 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             raise NSLCMException(
67                 'NS [id=%s] does not exist' % self.ns_instance_id)
68
69         self.update_type = ignore_case_get(self.request_data, "updateType")
70         if not self.update_type:
71             raise NSLCMException(
72                 'UpdateType parameter does not exist or value incorrect.')
73
74     def do_update(self):
75         if self.update_type == "OPERATE_VNF":
76             self.operate_vnf_data = ignore_case_get(
77                 self.request_data, "operateVnfData")
78             if not self.operate_vnf_data:
79                 raise NSLCMException(
80                     'OperateVnfData does not exist or value is incorrect.')
81             for vnf_update_data in self.operate_vnf_data:
82                 vnf_update_params = self.prepare_update_params(vnf_update_data)
83                 status = self.do_vnf_update(vnf_update_params, 15)
84                 if status is JOB_MODEL_STATUS.FINISHED:
85                     logger.info(
86                         'nf[%s] update handle end' % vnf_update_params.get('vnfInstanceId'))
87                     self.update_job(90,
88                                     desc='nf[%s] update handle end'
89                                          % vnf_update_params.get('vnfInstanceId'))
90                 else:
91                     raise NSLCMException('nf update failed')
92         else:
93             raise NSLCMException('Method update.')
94
95     def do_vnf_update(self, vnf_update_params, progress):
96         vnf_instance_id = vnf_update_params.get('vnfInstanceId')
97         nf_service = NFOperateService(vnf_instance_id, vnf_update_params)
98         nf_service.start()
99         self.update_job(progress, desc='nf[%s] update handle start' % vnf_instance_id)
100         status = self.wait_job_finish(nf_service.job_id)
101         return status
102
103     @staticmethod
104     def prepare_update_params(vnf_data):
105         vnf_instance_id = ignore_case_get(vnf_data, 'vnfInstanceId')
106         if not vnf_instance_id:
107             raise NSLCMException(
108                 'VnfInstanceId does not exist or value is incorrect.')
109
110         change_state_to = ignore_case_get(vnf_data, 'changeStateTo')
111         if not change_state_to:
112             raise NSLCMException(
113                 'ChangeStateTo does not exist or value is incorrect.')
114         graceful_stop_timeout = ''
115         operational_states = ignore_case_get(change_state_to, 'OperationalStates')
116         if operational_states == OPERATIONAL_STATE.STOPPED:
117             stop_type = ignore_case_get(vnf_data, 'stopType')
118             if stop_type == STOP_TYPE.GRACEFUL:
119                 graceful_stop_timeout = ignore_case_get(vnf_data, 'gracefulStopTimeout')
120
121         result = {
122             "vnfInstanceId": vnf_instance_id,
123             "changeStateTo": operational_states,
124             "stopType": stop_type,
125             "gracefulStopTimeout": graceful_stop_timeout if graceful_stop_timeout else 0
126         }
127         return result
128
129     @staticmethod
130     def wait_job_finish(sub_job_id, timeout=3600):
131         query_interval = 2
132         start_time = end_time = datetime.datetime.now()
133         while (end_time - start_time).seconds < timeout:
134             job_result = JobModel.objects.get(jobid=sub_job_id)
135             time.sleep(query_interval)
136             end_time = datetime.datetime.now()
137             if job_result.progress == JOB_PROGRESS.FINISHED:
138                 return JOB_MODEL_STATUS.FINISHED
139             elif job_result.progress > JOB_PROGRESS.FINISHED:
140                 return JOB_MODEL_STATUS.ERROR
141             else:
142                 continue
143         return JOB_MODEL_STATUS.TIMEOUT
144
145     def update_job(self, progress, desc=''):
146         JobUtil.add_job_status(self.job_id, progress, desc)
147
148     def update_ns_status(self, status):
149         NSInstModel.objects.filter(id=self.ns_instance_id).update(status=status)