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