Updating the VNF policy translation
[optf/osdf.git] / osdf / optimizers / placementopt / conductor / translation.py
1 # -------------------------------------------------------------------------
2 #   Copyright (c) 2015-2017 AT&T Intellectual Property
3 #
4 #   Licensed under the Apache License, Version 2.0 (the "License");
5 #   you may not use this file except in compliance with the License.
6 #   You may obtain a copy of the License at
7 #
8 #       http://www.apache.org/licenses/LICENSE-2.0
9 #
10 #   Unless required by applicable law or agreed to in writing, software
11 #   distributed under the License is distributed on an "AS IS" BASIS,
12 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 #   See the License for the specific language governing permissions and
14 #   limitations under the License.
15 #
16 # -------------------------------------------------------------------------
17 #
18 import copy
19 import json
20 import yaml
21
22 from osdf.utils.data_conversion import text_to_symbol
23 from osdf.utils.programming_utils import dot_notation
24
25 policy_config_mapping = yaml.load(open('config/has_config.yaml')).get('policy_config_mapping')
26
27
28 def get_opt_query_data(req_json, policies):
29     """
30     Fetch service and order specific details from the requestParameters field of a request.
31     :param req_json: a request file
32     :param policies: A set of policies
33     :return: A dictionary with service and order-specific attributes.
34     """
35     req_param_dict = {}
36     if 'requestParameters' in req_json["placementInfo"]:
37         req_params = req_json["placementInfo"]["requestParameters"]
38         for policy in policies:
39             for queryProp in policy['content']['queryProperties']:
40                 attr_val = queryProp['value'] if 'value' in queryProp and queryProp['value'] != "" \
41                     else dot_notation(req_params, queryProp['attribute_location'])
42                 if attr_val is not None:
43                     req_param_dict.update({queryProp['attribute']: attr_val})
44     return req_param_dict
45
46
47 def gen_optimization_policy(vnf_list, optimization_policy):
48     """Generate optimization policy details to pass to Conductor
49     :param vnf_list: List of vnf's to used in placement request
50     :param optimization_policy: optimization objective policy information provided in the incoming request
51     :return: List of optimization objective policies in a format required by Conductor
52     """
53     optimization_policy_list = []
54     for policy in optimization_policy:
55         content = policy['content']
56         parameter_list = []
57
58         for attr in content['objectiveParameter']['parameterAttributes']:
59             parameter = attr['parameter'] if attr['parameter'] == "cloud_version" else attr['parameter']+"_between"
60             vnfs = get_matching_vnfs(attr['resources'], vnf_list)
61             for vnf in vnfs:
62                 value = [vnf] if attr['parameter'] == "cloud_version" else [attr['customerLocationInfo'], vnf]
63                 parameter_list.append({
64                     attr['operator']: [attr['weight'], {parameter: value}]
65                 })
66
67         optimization_policy_list.append({
68                 content['objective']: {content['objectiveParameter']['operator']: parameter_list }
69         })
70     return optimization_policy_list
71
72
73 def get_matching_vnfs(resources, vnf_list, match_type="intersection"):
74     """Get a list of matching VNFs from the list of resources
75     :param resources:
76     :param vnf_list: List of vnfs to used in placement request
77     :param match_type: "intersection" or "all" or "any" (any => send all_vnfs if there is any intersection)
78     :return: List of matching VNFs
79     """
80     if match_type == "all":  # don't bother with any comparisons
81         return resources if set(resources) <= set(vnf_list) else None
82     common_vnfs = set(vnf_list) & set(resources)
83     if match_type == "intersection":  # specifically requested intersection
84         return list(common_vnfs)
85     return resources if common_vnfs else None  # "any" match => all resources to be returned
86
87
88 def gen_policy_instance(vnf_list, resource_policy, match_type="intersection", rtype=None):
89     """Generate a list of policies
90     :param vnf_list: List of vnf's to used in placement request
91     :param resource_policy: policy for this specific resource
92     :param match_type: How to match the vnf_names with the vnf_list (intersection or "any")
93              intersection => return intersection; "any" implies return all vnf_names if intersection is not null
94     :param rtype: resource type (e.g. resourceRegionProperty or resourceInstanceProperty)
95              None => no controller information added to the policy specification to Conductor
96     :return: resource policy list in a format required by Conductor
97     """
98     resource_policy_list = []
99     related_policies = []
100     for policy in resource_policy:
101         pc = policy['content']
102         demands = get_matching_vnfs(pc['resources'], vnf_list, match_type=match_type)
103         resource = {pc['identity']: {'type': pc['policyType'], 'demands': demands}}
104
105         if rtype:
106             resource[pc['identity']]['properties'] = {'controller': pc[rtype]['controller'],
107                                                       'request': json.loads(pc[rtype]['request'])}
108         if demands and len(demands) != 0:
109             resource_policy_list.append(resource)
110             related_policies.append(policy)
111     return resource_policy_list, related_policies
112
113
114 def gen_resource_instance_policy(vnf_list, resource_instance_policy):
115     """Get policies governing resource instances in order to populate the Conductor API call"""
116     cur_policies, _ = gen_policy_instance(vnf_list, resource_instance_policy, rtype='resourceInstanceProperty')
117     return cur_policies
118
119
120 def gen_resource_region_policy(vnf_list, resource_region_policy):
121     """Get policies governing resource region in order to populate the Conductor API call"""
122     cur_policies, _ = gen_policy_instance(vnf_list, resource_region_policy, rtype='resourceRegionProperty')
123     return cur_policies
124
125
126 def gen_inventory_group_policy(vnf_list, inventory_group_policy):
127     """Get policies governing inventory group in order to populate the Conductor API call"""
128     cur_policies, _ = gen_policy_instance(vnf_list, inventory_group_policy, rtype=None)
129     return cur_policies
130
131
132 def gen_reservation_policy(vnf_list, reservation_policy):
133     """Get policies governing resource instances in order to populate the Conductor API call"""
134     cur_policies, _ = gen_policy_instance(vnf_list, reservation_policy, rtype='instanceReservationProperty')
135     return cur_policies
136
137
138 def gen_distance_to_location_policy(vnf_list, distance_to_location_policy):
139     """Get policies governing distance-to-location for VNFs in order to populate the Conductor API call"""
140     cur_policies, related_policies = gen_policy_instance(vnf_list, distance_to_location_policy, rtype=None)
141     for p_new, p_main in zip(cur_policies, related_policies):  # add additional fields to each policy
142         properties = p_main['content']['distanceProperties']
143         pcp_d = properties['distance']
144         p_new[p_main['content']['identity']]['properties'] = {
145             'distance': pcp_d['operator'] + " " + pcp_d['value'].lower() + " " + pcp_d['unit'].lower(),
146             'location': properties['locationInfo']
147         }
148     return cur_policies
149
150
151 def gen_attribute_policy(vnf_list, attribute_policy):
152     """Get policies governing attributes of VNFs in order to populate the Conductor API call"""
153     cur_policies, related_policies = gen_policy_instance(vnf_list, attribute_policy, rtype=None)
154     for p_new, p_main in zip(cur_policies, related_policies):  # add additional fields to each policy
155         properties = p_main['content']['cloudAttributeProperty']
156         attribute_mapping = policy_config_mapping['attributes']  # wanted attributes and mapping
157         p_new[p_main['content']['identity']]['properties'] = {
158             'evaluate': dict((k, properties.get(attribute_mapping.get(k))) for k in attribute_mapping.keys())
159         }
160     return cur_policies  # cur_policies gets updated in place...
161
162
163 def gen_zone_policy(vnf_list, zone_policy):
164     """Get zone policies in order to populate the Conductor API call"""
165     cur_policies, related_policies = gen_policy_instance(vnf_list, zone_policy, match_type="all", rtype=None)
166     for p_new, p_main in zip(cur_policies, related_policies):  # add additional fields to each policy
167         pmz = p_main['content']['affinityProperty']
168         p_new[p_main['content']['identity']]['properties'] = {'category': pmz['category'], 'qualifier': pmz['qualifier']}
169     return cur_policies
170
171
172 def gen_capacity_policy(vnf_list, capacity_policy):
173     """Get zone policies in order to populate the Conductor API call"""
174     cur_policies, related_policies = gen_policy_instance(vnf_list, capacity_policy, rtype=None)
175     for p_new, p_main in zip(cur_policies, related_policies):  # add additional fields to each policy
176         pmz = p_main['content']['capacityProperty']
177         p_new[p_main['content']['identity']]['properties'] = \
178             {"controller": pmz['controller'], 'request': json.loads(pmz['request'])}
179     return cur_policies
180
181
182 def gen_hpa_policy(vnf_list, hpa_policy):
183     """Get zone policies in order to populate the Conductor API call"""
184     cur_policies, related_policies = gen_policy_instance(vnf_list, hpa_policy, rtype=None)
185     for p_new, p_main in zip(cur_policies, related_policies):  # add additional fields to each policy
186         p_new[p_main['content']['identity']]['properties'] = {'evaluate': p_main['content']['flavorFeatures']}
187     return cur_policies
188
189
190 def get_augmented_policy_attributes(policy_property, demand):
191     """Get policy attributes and augment them using policy_config_mapping and demand information"""
192     attributes = copy.copy(policy_property['attributes'])
193     remapping = policy_config_mapping['remapping']
194     extra = dict((x, demand['resourceModelInfo'][remapping[x]]) for x in attributes if x in remapping)
195     attributes.update(extra)
196     return attributes
197
198
199 def get_candidates_demands(demand):
200     """Get demands related to candidates; e.g. excluded/required"""
201     res = {}
202     for k, v in policy_config_mapping['candidates'].items():
203         if k not in demand:
204             continue
205         res[v] = [{'inventory_type': x['candidateType'], 'candidate_id': x['candidates']} for x in demand[k]]
206     return res
207
208
209 def get_policy_properties(demand, policies):
210     """Get policy_properties for cases where there is a match with the demand"""
211     for policy in policies:
212         if demand['resourceModuleName'] not in set(policy['content'].get('resources', [])):
213             continue  # no match for this policy
214         for policy_property in policy['content']['vnfProperties']:
215             yield policy_property
216
217
218 def get_demand_properties(demand, policies):
219     """Get list demand properties objects (named tuples) from policy"""
220     demand_properties = []
221     for policy_property in get_policy_properties(demand, policies):
222         prop = dict(inventory_provider=policy_property['inventoryProvider'],
223                     inventory_type=policy_property['inventoryType'],
224                     service_type=demand['serviceResourceId'])
225         attributes = policy_config_mapping['attributes']
226         prop['attributes'] = {
227             'global-customer-id': policy_property['customerId'],
228             'orchestration-status': "",
229             'model-invariant-id': demand['resourceModelInfo']['modelInvariantId'],
230             'model-version-id': demand['resourceModelInfo']['modelVersionId'],
231             'service-type': demand['serviceResourceId'],
232             'equipment-role': policy_property['equipmentRole']
233         }
234         # if 'attributes' in policy_property:
235         #     prop['attributes'] = get_augmented_policy_attributes(policy_property, demand)
236         # for k1, v1, k2, v2 in policy_config_mapping['extra_fields']:
237         #     if k1 == v1:
238         #         prop[k2] = v2
239         prop.update(get_candidates_demands(demand))  # for excluded and partial-rehoming cases
240         demand_properties.append(prop)
241     return demand_properties
242
243
244 def gen_demands(req_json, vnf_policies):
245     """Generate list of demands based on request and VNF policies
246     :param req_json: Request object from the client (e.g. MSO)
247     :param vnf_policies: Policies associated with demand resources (e.g. from grouped_policies['vnfPolicy'])
248     :return: list of demand parameters to populate the Conductor API call
249     """
250     demand_dictionary = {}
251     for demand in req_json['placementInfo']['placementDemands']:
252         demand_dictionary.update(
253             {demand['resourceModuleName']: get_demand_properties(demand, vnf_policies)})
254     return demand_dictionary