Refactor logic of scale VNF
[vfc/nfvo/lcm.git] / lcm / ns / vnfs / scale_vnfs.py
1 # Copyright 2017 ZTE 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 import json
15 import logging
16 import threading
17 import traceback
18
19 from lcm.ns.vnfs.const import VNF_STATUS
20 from lcm.ns.vnfs.wait_job import wait_job_finish
21 from lcm.pub.database.models import NfInstModel
22 from lcm.pub.exceptions import NSLCMException
23 from lcm.pub.msapi.vnfmdriver import send_nf_scaling_request
24 from lcm.pub.utils.jobutil import JobUtil, JOB_TYPE, JOB_MODEL_STATUS
25 from lcm.pub.utils.values import ignore_case_get
26
27 JOB_ERROR = 255
28 SCALE_TYPE = ("SCALE_OUT", "SCALE_IN")
29 logger = logging.getLogger(__name__)
30
31
32 class NFManualScaleService(threading.Thread):
33     def __init__(self, vnf_instance_id, data):
34         super(NFManualScaleService, self).__init__()
35         self.vnf_instance_id = vnf_instance_id
36         self.data = data
37         self.job_id = JobUtil.create_job(
38             "NF", JOB_TYPE.MANUAL_SCALE_VNF, vnf_instance_id)
39         self.nf_scale_params = []
40         self.m_nf_inst_id = ''
41         self.vnfm_inst_id = ''
42
43     def run(self):
44         try:
45             self.do_biz()
46         except NSLCMException as e:
47             JobUtil.add_job_status(self.job_id, JOB_ERROR, e.message)
48         except Exception as ex:
49             logger.error(ex.message)
50             logger.error(traceback.format_exc())
51             JobUtil.add_job_status(self.job_id, JOB_ERROR, 'VNF scale failed')
52         finally:
53             self.update_nf_status()
54
55     def do_biz(self):
56         self.update_job(1, desc='VNF scale start')
57         self.update_nf_status(VNF_STATUS.SCALING)
58         self.get_and_check_params()
59         self.send_nf_scaling_requests()
60         self.update_job(100, desc='VNF scale success')
61
62     def get_and_check_params(self):
63         nf_info = NfInstModel.objects.filter(nfinstid=self.vnf_instance_id)
64         if not nf_info:
65             raise NSLCMException(
66                 'NF instance[id=%s] does not exist' %
67                 self.vnf_instance_id)
68         logger.debug('vnfd_model = %s, vnf_instance_id = %s' %
69                      (nf_info[0].vnfd_model, self.vnf_instance_id))
70         nf_model = json.loads(nf_info[0].vnfd_model)
71         self.m_nf_inst_id = nf_info[0].mnfinstid
72         self.vnfm_inst_id = nf_info[0].vnfm_inst_id
73         scale_vnf_data = ignore_case_get(self.data, 'scaleVnfData')
74         if not scale_vnf_data:
75             raise NSLCMException('scaleVnfData parameter does not exist')
76
77         self.nf_scale_params.append({
78             'type': ignore_case_get(scale_vnf_data, 'type'),
79             'aspectId': ignore_case_get(scale_vnf_data, 'aspectId'),
80             'numberOfSteps': ignore_case_get(scale_vnf_data, 'numberOfSteps'),
81             'additionalParam': {'vnfdModel': nf_model}
82         })
83
84     def send_nf_scaling_requests(self):
85         nf_scale_num = len(self.nf_scale_params)
86         for i in range(nf_scale_num):
87             progress_range = [10 + 80 / nf_scale_num * i,
88                               10 + 80 / nf_scale_num * (i + 1)]
89             self.send_nf_scaling_request(
90                 self.nf_scale_params[i], progress_range)
91
92     def send_nf_scaling_request(self, scale_param, progress_range):
93         req_param = json.JSONEncoder().encode(scale_param)
94         rsp = send_nf_scaling_request(
95             self.vnfm_inst_id, self.m_nf_inst_id, req_param)
96         vnfm_job_id = ignore_case_get(rsp, 'jobId')
97         ret = wait_job_finish(
98             self.vnfm_inst_id,
99             self.job_id,
100             vnfm_job_id,
101             progress_range=progress_range,
102             timeout=1200,
103             mode='1')
104         if ret != JOB_MODEL_STATUS.FINISHED:
105             raise NSLCMException("VNF scale failed")
106
107     def update_nf_status(self, status=VNF_STATUS.ACTIVE):
108         NfInstModel.objects.filter(
109             nfinstid=self.vnf_instance_id).update(
110             status=status)
111
112     def update_job(self, progress, desc=''):
113         JobUtil.add_job_status(self.job_id, progress, desc)