OSDF migration to new Policy API
[optf/osdf.git] / apps / placement / optimizers / 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 re
21
22 import yaml
23
24 from osdf.utils.programming_utils import dot_notation
25
26 policy_config_mapping = yaml.safe_load(open('config/has_config.yaml')).get('policy_config_mapping')
27
28
29 def get_opt_query_data(req_json, policies):
30     """
31     Fetch service and order specific details from the requestParameters field of a request.
32     :param req_json: a request file
33     :param policies: A set of policies
34     :return: A dictionary with service and order-specific attributes.
35     """
36     req_param_dict = {}
37     if 'requestParameters' in req_json["placementInfo"]:
38         req_params = req_json["placementInfo"]["requestParameters"]
39         for policy in policies:
40             for queryProp in policy[list(policy.keys())[0]]['properties']['queryProperties']:
41                 attr_val = queryProp['value'] if 'value' in queryProp and queryProp['value'] != "" \
42                     else dot_notation(req_params, queryProp['attribute_location'])
43                 if attr_val is not None:
44                     req_param_dict.update({queryProp['attribute']: attr_val})
45     return req_param_dict
46
47
48 def gen_optimization_policy(vnf_list, optimization_policy):
49     """Generate optimization policy details to pass to Conductor
50     :param vnf_list: List of vnf's to used in placement request
51     :param optimization_policy: optimization objective policy information provided in the incoming request
52     :return: List of optimization objective policies in a format required by Conductor
53     """
54     optimization_policy_list = []
55     for policy in optimization_policy:
56         content = policy[list(policy.keys())[0]]['properties']
57         parameter_list = []
58         parameters = ["cloud_version", "hpa_score"]
59
60         for attr in content['objectiveParameter']['parameterAttributes']:
61             parameter = attr['parameter'] if attr['parameter'] in parameters else attr['parameter']+"_between"
62             default, vnfs = get_matching_vnfs(attr['resources'], vnf_list)
63             for vnf in vnfs:
64                 value = [vnf] if attr['parameter'] in parameters else [attr['customerLocationInfo'], vnf]
65                 parameter_list.append({
66                     attr['operator']: [attr['weight'], {parameter: value}]
67                 })
68
69         optimization_policy_list.append({
70                 content['objective']: {content['objectiveParameter']['operator']: parameter_list }
71         })
72     return optimization_policy_list
73
74
75 def get_matching_vnfs(resources, vnf_list, match_type="intersection"):
76     """Get a list of matching VNFs from the list of resources
77     :param resources:
78     :param vnf_list: List of vnfs to used in placement request
79     :param match_type: "intersection" or "all" or "any" (any => send all_vnfs if there is any intersection)
80     :return: List of matching VNFs
81     """
82     # Check if it is a default policy
83     default = True if resources == [] else False
84     resources_lcase = [x.lower() for x in resources] if not default else [x.lower() for x in vnf_list]
85     if match_type == "all":  # don't bother with any comparisons
86         return default, resources if set(resources_lcase) <= set(vnf_list) else None
87     common_vnfs = set(vnf_list) & set(resources_lcase) if not default else set(vnf_list)
88     common_resources = [x for x in resources if x.lower() in common_vnfs] if not default else list(common_vnfs)
89     if match_type == "intersection":  # specifically requested intersection
90         return default, list(common_resources)
91     return default, resources if common_vnfs else None  # "any" match => all resources to be returned
92
93
94 def gen_policy_instance(vnf_list, resource_policy, match_type="intersection", rtype=None):
95     """Generate a list of policies
96     :param vnf_list: List of vnf's to used in placement request
97     :param resource_policy: policy for this specific resource
98     :param match_type: How to match the vnf_names with the vnf_list (intersection or "any")
99              intersection => return intersection; "any" implies return all vnf_names if intersection is not null
100     :param rtype: resource type (e.g. resourceRegionProperty or resourceInstanceProperty)
101              None => no controller information added to the policy specification to Conductor
102     :return: resource policy list in a format required by Conductor
103     """
104     resource_policy_list = []
105     related_policies = []
106     for policy in resource_policy:
107         pc = policy[list(policy.keys())[0]]
108         default, demands = get_matching_vnfs(pc['properties']['resources'], vnf_list, match_type=match_type)
109         resource = {pc['properties']['identity']: {'type': map_constraint_type(pc['type']), 'demands': demands}}
110
111         if rtype:
112             resource[pc['properties']['identity']]['properties'] = {'controller': pc[rtype]['controller'],
113                                                                     'request': json.loads(pc[rtype]['request'])}
114         if demands and len(demands) != 0:
115             # The default policy shall not override the specific policy that already appended
116             if default:
117                 for d in demands:
118                     resource_repeated = True \
119                         if {pc['properties']['identity']: {'type': map_constraint_type(pc['type']), 'demands': d}} \
120                            in resource_policy_list else False
121                     if resource_repeated:
122                         continue
123                     else:
124                         resource_policy_list.append(
125                             {pc['properties']['identity']: {'type': map_constraint_type(pc['type']), 'demands': d }})
126                         policy[list(policy.keys())[0]]['properties']['resources'] = d
127                         related_policies.append(policy)
128             # Need to override the default policies, here delete the outdated policy stored in the db
129             if resource in resource_policy_list:
130                 for pc in related_policies:
131                     if pc[list(pc.keys()[0])]['properties']['resources'] == resource:
132                         related_policies.remove(pc)
133                 resource_policy_list.remove(resource)
134             related_policies.append(policy)
135             resource_policy_list.append(resource)
136
137     return resource_policy_list, related_policies
138
139
140 def gen_resource_instance_policy(vnf_list, resource_instance_policy):
141     """Get policies governing resource instances in order to populate the Conductor API call"""
142     cur_policies, _ = gen_policy_instance(vnf_list, resource_instance_policy, rtype='resourceInstanceProperty')
143     return cur_policies
144
145
146 def gen_resource_region_policy(vnf_list, resource_region_policy):
147     """Get policies governing resource region in order to populate the Conductor API call"""
148     cur_policies, _ = gen_policy_instance(vnf_list, resource_region_policy, rtype='resourceRegionProperty')
149     return cur_policies
150
151
152 def gen_inventory_group_policy(vnf_list, inventory_group_policy):
153     """Get policies governing inventory group in order to populate the Conductor API call"""
154     cur_policies, _ = gen_policy_instance(vnf_list, inventory_group_policy, rtype=None)
155     return cur_policies
156
157
158 def gen_reservation_policy(vnf_list, reservation_policy):
159     """Get policies governing resource instances in order to populate the Conductor API call"""
160     cur_policies, _ = gen_policy_instance(vnf_list, reservation_policy, rtype='instanceReservationProperty')
161     return cur_policies
162
163
164 def gen_distance_to_location_policy(vnf_list, distance_to_location_policy):
165     """Get policies governing distance-to-location for VNFs in order to populate the Conductor API call"""
166     cur_policies, related_policies = gen_policy_instance(vnf_list, distance_to_location_policy, rtype=None)
167     for p_new, p_main in zip(cur_policies, related_policies):  # add additional fields to each policy
168         properties = p_main[list(p_main.keys())[0]]['properties']['distanceProperties']
169         pcp_d = properties['distance']
170         p_new[p_main[list(p_main.keys())[0]]['properties']['identity']]['properties'] = {
171             'distance': pcp_d['operator'] + " " + pcp_d['value'].lower() + " " + pcp_d['unit'].lower(),
172             'location': properties['locationInfo']
173         }
174     return cur_policies
175
176
177 def gen_attribute_policy(vnf_list, attribute_policy):
178     """Get policies governing attributes of VNFs in order to populate the Conductor API call"""
179     cur_policies, related_policies = gen_policy_instance(vnf_list, attribute_policy, rtype=None)
180     for p_new, p_main in zip(cur_policies, related_policies):  # add additional fields to each policy
181         properties = p_main[list(p_main.keys())[0]]['properties']['attributeProperties']
182         attribute_mapping = policy_config_mapping['filtering_attributes']  # wanted attributes and mapping
183         p_new[p_main[list(p_main.keys())[0]]['properties']['identity']]['properties'] = {
184             'evaluate': dict((attribute_mapping[k], properties.get(k) 
185                               if k != "cloudRegion" else gen_cloud_region(properties)) 
186                               for k in attribute_mapping.keys()) 
187         }
188     return cur_policies  # cur_policies gets updated in place...
189
190
191 def gen_zone_policy(vnf_list, zone_policy):
192     """Get zone policies in order to populate the Conductor API call"""
193     cur_policies, related_policies = gen_policy_instance(vnf_list, zone_policy, match_type="all", rtype=None)
194     for p_new, p_main in zip(cur_policies, related_policies):  # add additional fields to each policy
195         pmz = p_main[list(p_main.keys())[0]]['properties']['affinityProperties']
196         p_new[p_main[list(p_main.keys())[0]]['properties']['identity']]['properties'] = \
197             {'category': pmz['category'], 'qualifier': pmz['qualifier']}
198     return cur_policies
199
200
201 def gen_capacity_policy(vnf_list, capacity_policy):
202     """Get zone policies in order to populate the Conductor API call"""
203     cur_policies, related_policies = gen_policy_instance(vnf_list, capacity_policy, rtype=None)
204     for p_new, p_main in zip(cur_policies, related_policies):  # add additional fields to each policy
205         pmz = p_main[list(p_main.keys())[0]]['properties']['capacityProperty']
206         p_new[p_main[list(p_main.keys())[0]]['properties']['identity']]['properties'] = \
207             {"controller": pmz['controller'], 'request': json.loads(pmz['request'])}
208     return cur_policies
209
210
211 def gen_hpa_policy(vnf_list, hpa_policy):
212     """Get zone policies in order to populate the Conductor API call"""
213     cur_policies, related_policies = gen_policy_instance(vnf_list, hpa_policy, rtype=None)
214     for p_new, p_main in zip(cur_policies, related_policies):  # add additional fields to each policy
215         p_new[p_main[list(p_main.keys())[0]]['properties']['identity']]['properties'] = \
216             {'evaluate': p_main[list(p_main.keys())[0]]['properties']['flavorFeatures']}
217     return cur_policies
218
219
220 def get_augmented_policy_attributes(policy_property, demand):
221     """Get policy attributes and augment them using policy_config_mapping and demand information"""
222     attributes = copy.copy(policy_property['attributes'])
223     remapping = policy_config_mapping['remapping']
224     extra = dict((x, demand['resourceModelInfo'][remapping[x]]) for x in attributes if x in remapping)
225     attributes.update(extra)
226     return attributes
227
228
229 def get_candidates_demands(demand):
230     """Get demands related to candidates; e.g. excluded/required"""
231     res = {}
232     for k, v in policy_config_mapping['candidates'].items():
233         if k not in demand:
234             continue
235         res[v] = [{'inventory_type': x['identifierType'], 'candidate_id': x['identifiers']} for x in demand[k]]
236     return res
237
238
239 def get_policy_properties(demand, policies):
240     """Get policy_properties for cases where there is a match with the demand"""
241     for policy in policies:
242         policy_demands = set([x.lower() for x in policy[list(policy.keys())[0]]['properties']['resources']])
243         if policy_demands and demand['resourceModuleName'].lower() not in policy_demands:
244             continue  # no match for this policy
245         elif policy_demands == set(): # Append resource name for default policy
246             policy[list(policy.keys())[0]]['properties'].update(resources=list(demand.get('resourceModuleName')))
247         for policy_property in policy[list(policy.keys())[0]]['properties']['vnfProperties']:
248             yield policy_property
249
250
251 def get_demand_properties(demand, policies):
252     """Get list demand properties objects (named tuples) from policy"""
253     demand_properties = []
254     for policy_property in get_policy_properties(demand, policies):
255         prop = dict(inventory_provider=policy_property['inventoryProvider'],
256                     inventory_type=policy_property['inventoryType'],
257                     service_type=demand['serviceResourceId'],
258                     service_resource_id=demand['serviceResourceId'])
259
260         prop.update({'unique': policy_property['unique']} if 'unique' in policy_property and
261                                                              policy_property['unique'] else {})
262         prop['filtering_attributes'] = dict()
263         prop['filtering_attributes'].update({'global-customer-id': policy_property['customerId']}
264                                   if policy_property['customerId'] else {})
265         prop['filtering_attributes'].update({'model-invariant-id': demand['resourceModelInfo']['modelInvariantId']}
266                                   if demand['resourceModelInfo']['modelInvariantId'] else {})
267         prop['filtering_attributes'].update({'model-version-id': demand['resourceModelInfo']['modelVersionId']}
268                                   if demand['resourceModelInfo']['modelVersionId'] else {})
269         prop['filtering_attributes'].update({'equipment-role': policy_property['equipmentRole']}
270                                   if policy_property['equipmentRole'] else {})
271
272         if policy_property.get('attributes'):
273             for attr_key, attr_val in policy_property['attributes'].items():
274                 update_converted_attribute(attr_key, attr_val, prop, 'filtering_attributes')
275         if policy_property.get('passthroughAttributes'):
276             prop['passthrough_attributes'] = dict()
277             for attr_key, attr_val in policy_property['passthroughAttributes'].items():
278                 update_converted_attribute(attr_key, attr_val, prop, 'passthrough_attributes')
279
280         prop.update(get_candidates_demands(demand))
281         demand_properties.append(prop)
282     return demand_properties
283
284
285 def update_converted_attribute(attr_key, attr_val, properties, attribute_type):
286     """
287     Updates dictonary of attributes with one specified in the arguments.
288     Automatically translates key namr from camelCase to hyphens
289     :param attribute_type: attribute section name
290     :param attr_key: key of the attribute
291     :param attr_val: value of the attribute
292     :param properties: dictionary with attributes to update
293     :return:
294     """
295     if attr_val:
296         remapping = policy_config_mapping[attribute_type]
297         if remapping.get(attr_key):
298             key_value = remapping.get(attr_key)
299         else:
300             key_value = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', attr_key)
301             key_value = re.sub('([a-z0-9])([A-Z])', r'\1-\2', key_value).lower()
302         properties[attribute_type].update({key_value: attr_val})
303
304
305 def gen_demands(req_json, vnf_policies):
306     """Generate list of demands based on request and VNF policies
307     :param req_json: Request object from the client (e.g. MSO)
308     :param vnf_policies: Policies associated with demand resources (e.g. from grouped_policies['vnfPolicy'])
309     :return: list of demand parameters to populate the Conductor API call
310     """
311     demand_dictionary = {}
312     for demand in req_json['placementInfo']['placementDemands']:
313         prop = get_demand_properties(demand, vnf_policies)
314         if len(prop) > 0:
315             demand_dictionary.update({demand['resourceModuleName']: prop})
316     return demand_dictionary
317
318
319 def map_constraint_type(policy_type):
320     if "onap.policies.optimization.AttributePolicy" == policy_type:
321         return "attribute"
322     if "onap.policies.optimization.DistancePolicy" == policy_type:
323         return "distance_to_location"
324     if "onap.policies.optimization.InventoryGroupPolicy" == policy_type:
325         return "inventory_group"
326     if "onap.policies.optimization.ResourceInstancePolicy" == policy_type:
327         return "instance_fit"
328     if "onap.policies.optimization.ResourceRegionPolicy" == policy_type:
329         return "region_fit"
330     if "onap.policies.optimization.AffinityPolicy" == policy_type:
331         return "zone"
332     if "onap.policies.optimization.InstanceReservationPolicy" == policy_type:
333         return "instance_reservation"
334     if "onap.policies.optimization.Vim_fit" == policy_type:
335         return "vim_fit"
336     if "onap.policies.optimization.HpaPolicy" == policy_type:
337         return "hpa"
338     
339     return policy_type
340
341
342 def gen_cloud_region(property):
343     prop = {"cloud_region_attributes": dict()}
344     if 'cloudRegion' in property:
345         for k,v in property['cloudRegion'].items():
346             update_converted_attribute(k, v, prop, 'cloud_region_attributes')
347     return prop["cloud_region_attributes"]