dda1797e873af1de4fd2e9f09df4413cbf2f275a
[vfc/nfvo/lcm.git] / lcm / pub / utils / scaleaspect.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
15 import json
16 import os
17 import logging
18 from lcm.pub.exceptions import NSLCMException
19 from rest_framework import status
20 from rest_framework.response import Response
21 from rest_framework.views import APIView
22 from rest_framework import status
23 from rest_framework.response import Response
24
25 logger = logging.getLogger(__name__)
26 SCALE_TYPE = ("SCALE_NS", "SCALE_VNF")
27
28 scale_vnf_data_mapping = {
29     "vnfInstanceId":"",
30     "scaleByStepData":[
31         {
32             "type":"",
33             "aspectId":"",
34             "numberOfSteps":""
35         }
36     ]
37 }
38
39 def ignorcase_get(args, key):
40     if not key:
41         return ""
42     if not args:
43         return ""
44     if key in args:
45         return args[key]
46     for old_key in args:
47         if old_key.upper() == key.upper():
48             return args[old_key]
49     return ""
50
51 def mapping_conv(keyword_map, rest_return):
52     resp_data = {}
53     for param in keyword_map:
54         if keyword_map[param]:
55             if isinstance(keyword_map[param], dict):
56                 resp_data[param] = mapping_conv(keyword_map[param], ignorcase_get(rest_return, param))
57             else:
58                 resp_data[param] = ignorcase_get(rest_return, param)
59     return resp_data
60
61 def get_vnf_scale_info(filename, ns_instanceId, aspect, step):
62     json_data = get_json_data(filename)
63     scale_options = ignorcase_get(json_data, "scale_options")
64     for i in range(scale_options.__len__()):
65         ns_scale_option = scale_options[i]
66         if (ignorcase_get(ns_scale_option, "ns_instanceId") == ns_instanceId) \
67                 and (ignorcase_get(ns_scale_option, "ns_scale_aspect") == aspect):
68             ns_scale_info_list = ignorcase_get(ns_scale_option, "ns_scale_info_list")
69             for j in range(ns_scale_info_list.__len__()):
70                 ns_scale_info = ns_scale_info_list[j]
71                 if ns_scale_info["step"] == step:
72                     return ns_scale_info["vnf_scale_list"]
73
74     return None
75
76 def get_json_data(filename):
77     f = open(filename)
78     json_str = f.read()
79     data = json.JSONDecoder().decode(json_str)
80     f.close()
81     return data
82
83 def check_scale_list(vnf_scale_list, ns_instanceId, aspect, step):
84     if vnf_scale_list is None:
85         logger.debug("The scaling option[ns=%s, aspect=%s, step=%s] does not exist. Pls check the config file." %(ns_instanceId, aspect, step))
86         raise Exception("The scaling option[ns=%s, aspect=%s, step=%s] does not exist. Pls check the config file." %(ns_instanceId, aspect, step))
87     else:
88         return vnf_scale_list
89
90 def set_scaleVnfData_type(vnf_scale_list, scale_type):
91     logger.debug("vnf_scale_list = %s, type = %s" % (vnf_scale_list, scale_type))
92     scaleVnfDataList = []
93     if vnf_scale_list is not None:
94         for i in range(vnf_scale_list.__len__()):
95             scaleVnfData = scale_vnf_data_mapping
96             scaleVnfData["vnfInstanceId"] = get_vnfInstanceIdByName(vnf_scale_list[i]["vnfInstanceId"])
97             scaleVnfData["scaleByStepData"][0]["type"] = scale_type
98             scaleVnfData["scaleByStepData"][0]["aspectId"] = vnf_scale_list[i]["vnf_scaleAspectId"]
99             scaleVnfData["scaleByStepData"][0]["numberOfSteps"] = vnf_scale_list[i]["numberOfSteps"]
100             scaleVnfDataList.append(scaleVnfData)
101     logger.debug("scaleVnfDataList = %s" % scaleVnfDataList)
102     return scaleVnfDataList
103
104 def get_vnfInstanceIdByName(name):
105     return name
106
107 def get_vnf_data(filename, ns_instanceId, aspect, step, scale_type):
108
109     vnf_scale_list = get_vnf_scale_info(filename, ns_instanceId, aspect, step)
110     check_scale_list(vnf_scale_list, ns_instanceId, aspect, step)
111     scaleVnfDataList = set_scaleVnfData_type(vnf_scale_list,scale_type)
112     logger.debug("scaleVnfDataList = %s" % scaleVnfDataList)
113     return scaleVnfDataList
114
115     #return Response(data={'error': e.message},status=status.HTTP_204_NO_CONTENT)
116     #return Response(data={'success': 'success'},status=status.HTTP_200_OK)
117
118 def get_and_check_params(scaleNsData, ns_InstanceId):
119
120     if scaleNsData is None:
121         pass
122         #raise NSLCMException("Error! scaleNsData in the request is Empty!")
123
124     scaleNsByStepsData = scaleNsData[0]["scaleNsByStepsData"]
125     if scaleNsByStepsData is None:
126         pass
127         #raise NSLCMException("Error! scaleNsByStepsData in the request is Empty!")
128
129     aspect = scaleNsByStepsData[0]["aspectId"]
130     numberOfSteps = scaleNsByStepsData[0]["numberOfSteps"]
131     scale_type = scaleNsByStepsData[0]["scalingDirection"]
132
133     return ns_InstanceId,aspect,numberOfSteps,scale_type
134
135 def get_scale_vnf_data(scaleNsData, ns_InstanceId):
136     curdir_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
137     filename = curdir_path + "/ns/data/scalemapping.json"
138     logger.debug("filename = %s" % filename)
139     ns_InstanceId,aspect,numberOfSteps,scale_type = get_and_check_params(scaleNsData, ns_InstanceId)
140     return get_vnf_data(filename, ns_InstanceId,aspect,numberOfSteps,scale_type)