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