Add scale vnf biz logic
[vfc/gvnfm/vnflcm.git] / lcm / lcm / nf / biz / scale_vnf.py
1 # Copyright (C) 2018 Verizon. All Rights Reserved.
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 uuid
17 import traceback
18 from threading import Thread
19
20 from lcm.nf.biz import common
21 from lcm.nf.biz.grant_vnf import grant_resource
22 from lcm.nf.const import VNF_STATUS, GRANT_TYPE, CHANGE_TYPE
23 from lcm.nf.const import RESOURCE_MAP, OPERATION_STATE_TYPE
24 from lcm.nf.const import INSTANTIATION_STATE
25 from lcm.pub.database.models import NfInstModel
26 from lcm.pub.database.models import VNFCInstModel, PortInstModel
27 from lcm.pub.database.models import VmInstModel
28 from lcm.pub.exceptions import NFLCMException
29 from lcm.pub.utils.notificationsutil import NotificationsUtil, prepare_notification
30 from lcm.pub.utils.values import ignore_case_get
31 from lcm.pub.utils.jobutil import JobUtil
32 from lcm.pub.utils.timeutil import now_time
33 from lcm.pub.vimapi import adaptor
34
35 logger = logging.getLogger(__name__)
36
37 DEFAULT_STEPS = 1
38
39
40 class ScaleVnf(Thread):
41     def __init__(self, data, nf_inst_id, job_id):
42         super(ScaleVnf, self).__init__()
43         self.data = data
44         self.nf_inst_id = nf_inst_id
45         self.job_id = job_id
46         self.vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
47
48     def run(self):
49         try:
50             self.heal_pre()
51             self.apply_grant()
52             self.do_operation()
53             JobUtil.add_job_status(self.job_id,
54                                    100,
55                                    "Scale Vnf success.")
56             self.vnf_insts.update(status=INSTANTIATION_STATE.INSTANTIATED,
57                                   lastuptime=now_time())
58         except NFLCMException as e:
59             logger.error(e.message)
60             self.vnf_scale_failed_handle(e.message)
61         except Exception as e:
62             logger.error(e.message)
63             logger.error(traceback.format_exc())
64             self.vnf_scale_failed_handle(e.message)
65
66     def scale_pre(self):
67         self.scale_type = self.data.get("type")
68         self.aspect_id = self.data.get("aspectId")
69         self.number_of_steps = int(self.data.get("numberOfSteps", DEFAULT_STEPS))
70         self.additional_params = self.data.get("additionalParams", {})
71         self.is_scale_in = (self.scale_type == GRANT_TYPE.SCALE_IN)
72         self.vnfd_info = json.loads(self.vnf_insts[0].vnfd_model)
73         self.step_delta = self.get_scale_step_delta()
74         self.target_vdu, self.step_inst_num = self.get_vdu_scale_aspect_deltas()
75         self.scale_inst_num = self.number_of_steps * self.step_inst_num
76         self.min_instance_num, self.max_instance_num = self.get_instance_range()
77         self.check_if_can_scale()
78         self.scale_out_resource = {}
79
80     def apply_grant(self):
81         logger.debug("Start scale apply grant")
82         vdus = ignore_case_get(self.vnfd_info, "vdus")
83         scale_vdus = [vdu for vdu in vdus if vdu["vdu_id"] == self.target_vdu]
84         scale_vdus = scale_vdus * self.scale_inst_num
85         grant_result = grant_resource(data=self.data,
86                                       nf_inst_id=self.nf_inst_id,
87                                       job_id=self.job_id,
88                                       grant_type=self.scale_type,
89                                       vdus=scale_vdus)
90         logger.debug("Scale Grant result: %s", grant_result)
91         self.set_location(grant_result)
92
93     def do_operation(self):
94         logger.debug("Start %s VNF resource", self.scale_type)
95         logger.debug('VnfdInfo = %s' % self.vnfd_info)
96
97         if self.is_scale_in:
98             self.affected_vnfcs = []
99             self.scale_in_resource = self.get_scale_in_resource(self.affected_vnfcs)
100             adaptor.delete_vim_res(self.scale_in_resource, self.do_notify_del_vim_res)
101         else:
102             self.scale_out_resource = {
103                 'volumn': [],
104                 'network': [],
105                 'subnet': [],
106                 'port': [],
107                 'flavor': [],
108                 'vm': []
109             }
110             self.vnfd_info["volume_storages"] = []
111             self.vnfd_info["vls"] = []
112             self.vnfd_info["cps"] = self.vnfd_info["cps"] * self.scale_inst_num
113             for cp in self.vnfd_info["cps"]:
114                 # TODO: how to set name for scale_out cp
115                 cp["properties"]["name"] = cp["cp_id"] + str(uuid.uuid4())
116                 cp_inst = PortInstModel.objects.filter(name__startswith=cp["cp_id"]).first()
117                 if cp_inst:
118                     cp["networkId"] = cp_inst.networkid
119                     cp["subnetId"] = cp_inst.subnetworkid
120                 else:
121                     raise NFLCMException("CP(%s) does not exist" % cp["cp_id"])
122             self.vnfd_info["vdus"] = self.vnfd_info["vdus"] * self.scale_inst_num
123             for vdu in self.vnfd_info["vdus"]:
124                 # TODO: how to set name for scale_out vdu
125                 vdu["properties"]["name"] = vdu["properties"]["name"] + str(uuid.uuid4())
126
127             vim_cache = json.loads(self.vnf_insts[0].vimInfo)
128             res_cache = json.loads(self.vnf_insts[0].resInfo)
129             adaptor.create_vim_res(self.vnfd_info,
130                                    self.do_notify_create_vim_res,
131                                    vim_cache=vim_cache,
132                                    res_cache=res_cache)
133             self.vnf_insts.update(vimInfo=json.dumps(vim_cache),
134                                   resInfo=json.dumps(res_cache))
135         logger.debug("%s VNF resource finish", self.scale_type)
136
137     def send_notification(self):
138         data = prepare_notification(nfinstid=self.nf_inst_id,
139                                     jobid=self.job_id,
140                                     operation=self.op_type,
141                                     operation_state=OPERATION_STATE_TYPE.COMPLETED)
142
143         # TODO: need set changedExtConnectivity for data
144         if self.is_scale_in:
145             data["affectedVnfcs"] = self.affected_vnfcs
146         else:
147             for vm in self.scale_out_resource["vm"]:
148                 self.set_affected_vnfcs(data["affectedVnfcs"], vm["res_id"])
149
150         logger.debug('Notify request data = %s' % data)
151         NotificationsUtil().send_notification(data)
152
153     def rollback_operation(self):
154         if self.is_scale_in:
155             # SCALE_IN operaion does not support rollback
156             return
157         adaptor.delete_vim_res(self.scale_out_resource, self.do_notify_del_vim_res)
158
159     def set_location(self, grant_result):
160         vim_connections = ignore_case_get(grant_result, "vimConnections")
161         access_info = ignore_case_get(vim_connections[0], "accessInfo")
162         tenant = ignore_case_get(access_info, "tenant")
163         vimid = ignore_case_get(vim_connections[0], "vimId")
164
165         for resource_type in ['vdus', 'vls', 'cps', 'volume_storages']:
166             for resource in ignore_case_get(self.vnfd_info, resource_type):
167                 if "location_info" not in resource["properties"]:
168                     resource["properties"]["location_info"] = {}
169                 resource["properties"]["location_info"]["vimid"] = vimid
170                 resource["properties"]["location_info"]["tenant"] = tenant
171
172     def do_notify_create_vim_res(self, res_type, ret):
173         logger.debug('Scaling out [%s] resource' % res_type)
174         resource_save_method = getattr(common, res_type + '_save')
175         resource_save_method(self.job_id, self.nf_inst_id, ret)
176         self.scale_out_resource[res_type].append(self.gen_del_resource(ret))
177
178     def do_notify_del_vim_res(self, res_type, res_id):
179         logger.debug('Scaling in [%s] resource, resourceid [%s]', res_type, res_id)
180         resource_type = RESOURCE_MAP.keys()[RESOURCE_MAP.values().index(res_type)]
181         resource_table = globals().get(resource_type + 'InstModel')
182         resource_table.objects.filter(instid=self.nf_inst_id, resourceid=res_id).delete()
183         if res_type == "vm":
184             VNFCInstModel.objects.filter(instid=self.nf_inst_id, vmid=res_id).delete()
185
186     def get_scale_in_resource(self, affected_vnfcs):
187         scale_in_resource = {
188             'volumn': [],
189             'network': [],
190             'subnet': [],
191             'port': [],
192             'flavor': [],
193             'vm': []
194         }
195         scale_in_vms = VmInstModel.objects.filter(instid=self.nf_inst_id)
196         vms_count = scale_in_vms.count()
197         for index in range(self.scale_inst_num):
198             vm_index = vms_count - index - 1
199             scale_in_resource["vm"].append(self.gen_del_resource(scale_in_vms[vm_index]))
200             self.set_affected_vnfcs(affected_vnfcs, scale_in_vms[vm_index].resourceid)
201         return scale_in_resource
202
203     def gen_del_resource(self, res):
204         is_dict = isinstance(res, dict)
205         return {
206             "vim_id": res["vimId"] if is_dict else res.vimid,
207             "tenant_id": res["tenantId"] if is_dict else res.tenant,
208             "res_id": res["id"] if is_dict else res.resourceid,
209             "is_predefined": res["returnCode"] if is_dict else res.is_predefined
210         }
211
212     def get_scale_step_delta(self):
213         for policy in self.vnfd_info.get("policies", []):
214             if policy.get("type") != "tosca.policies.nfv.ScalingAspects":
215                 continue
216             aspects = policy["properties"]["aspects"]
217             if self.aspect_id in aspects:
218                 return aspects.get(self.aspect_id).get("step_deltas")[0]
219         raise NFLCMException("Aspect(%s) does not exist" % self.aspect_id)
220
221     def get_vdu_scale_aspect_deltas(self):
222         for policy in self.vnfd_info.get("policies", []):
223             if policy.get("type") != "tosca.policies.nfv.VduScalingAspectDeltas":
224                 continue
225             target = policy.get("targets")[0]
226             deltas = policy["properties"]["deltas"]
227             if self.step_delta in deltas:
228                 num = int(deltas.get(self.step_delta).get("number_of_instances"))
229                 return target, num
230         raise NFLCMException("Aspect step delta(%s) does not exist" % self.step_delta)
231
232     def get_instance_range(self):
233         for vdu in self.vnfd_info["vdus"]:
234             if vdu["vdu_id"] == self.target_vdu:
235                 vdu_profile = vdu["properties"]["vdu_profile"]
236                 min_inst_num = int(vdu_profile["min_number_of_instances"])
237                 max_inst_num = int(vdu_profile["max_number_of_instances"])
238                 return min_inst_num, max_inst_num
239         raise NFLCMException("VDU(%s) does not exist" % self.target_vdu)
240
241     def check_if_can_scale(self):
242         cur_inst_num = VNFCInstModel.objects.filter(instid=self.nf_inst_id).count()
243         if self.is_scale_in:
244             if cur_inst_num - self.scale_inst_num < self.min_instance_num:
245                 msg = "VNF(%s) cannot be scaled: less than min instance."
246                 raise NFLCMException(msg % self.nf_inst_id)
247         else:
248             if cur_inst_num + self.scale_inst_num > self.max_instance_num:
249                 msg = "VNF(%s) cannot be scaled: max instance exceeded."
250                 raise NFLCMException(msg % self.nf_inst_id)
251
252     def set_affected_vnfcs(self, affected_vnfcs, vm_id):
253         chgtype = CHANGE_TYPE.REMOVED if self.is_scale_in else CHANGE_TYPE.ADDED
254         vnfcs = VNFCInstModel.objects.filter(instid=self.nf_inst_id, vmid=vm_id)
255         vm = VmInstModel.objects.filter(instid=self.nf_inst_id, resourceid=vm_id)
256         vm_resource = {}
257         if vm:
258             vm_resource = {
259                 'vimConnectionId': vm[0].vimid,
260                 'resourceId': vm[0].resourceid,
261                 'vimLevelResourceType': 'vm'
262             }
263         if vnfcs:
264             affected_vnfcs.append({
265                 'id': vnfcs[0].vnfcinstanceid,
266                 'vduId': vnfcs[0].vduid,
267                 'changeType': chgtype,
268                 'computeResource': vm_resource
269             })
270
271     def vnf_scale_failed_handle(self, error_msg):
272         logger.error('VNF scaling failed, detail message: %s', error_msg)
273         self.vnf_insts.update(status=VNF_STATUS.FAILED,
274                               lastuptime=now_time())
275         JobUtil.add_job_status(self.job_id, 255, error_msg)