1 # -------------------------------------------------------------------------
2 # Copyright (c) 2015-2017 AT&T Intellectual Property
3 # Copyright (C) 2020 Wipro Limited.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # -------------------------------------------------------------------------
24 from osdf.utils.programming_utils import dot_notation
26 policy_config_mapping = yaml.safe_load(open('config/has_config.yaml')).get('policy_config_mapping')
28 CONSTRAINT_TYPE_MAP = {"onap.policies.optimization.resource.AttributePolicy": "attribute",
29 "onap.policies.optimization.resource.DistancePolicy": "distance_to_location",
30 "onap.policies.optimization.resource.InventoryGroupPolicy": "inventory_group",
31 "onap.policies.optimization.resource.ResourceInstancePolicy": "instance_fit",
32 "onap.policies.optimization.resource.ResourceRegionPolicy": "region_fit",
33 "onap.policies.optimization.resource.AffinityPolicy": "zone",
34 "onap.policies.optimization.resource.InstanceReservationPolicy":
35 "instance_reservation",
36 "onap.policies.optimization.resource.Vim_fit": "vim_fit",
37 "onap.policies.optimization.resource.HpaPolicy": "hpa",
38 "onap.policies.optimization.resource.ThresholdPolicy": "threshold",
39 "onap.policies.optimization.resource.AggregationPolicy": "aggregation"
43 def get_opt_query_data(request_parameters, policies):
45 Fetch service and order specific details from the requestParameters field of a request.
46 :param request_parameters: A list of request parameters
47 :param policies: A set of policies
48 :return: A dictionary with service and order-specific attributes.
51 if request_parameters:
52 for policy in policies:
53 for queryProp in policy[list(policy.keys())[0]]['properties']['queryProperties']:
54 attr_val = queryProp['value'] if 'value' in queryProp and queryProp['value'] != "" \
55 else dot_notation(request_parameters, queryProp['attribute_location'])
56 if attr_val is not None:
57 req_param_dict.update({queryProp['attribute']: attr_val})
61 def gen_optimization_policy(vnf_list, optimization_policy):
62 """Generate optimization policy details to pass to Conductor
63 :param vnf_list: List of vnf's to used in placement request
64 :param optimization_policy: optimization objective policy information provided in the incoming request
65 :return: List of optimization objective policies in a format required by Conductor
67 optimization_policy_list = []
68 for policy in optimization_policy:
69 content = policy[list(policy.keys())[0]]['properties']
71 parameters = ["cloud_version", "hpa_score"]
73 for attr in content['objectiveParameter']['parameterAttributes']:
74 parameter = attr['parameter'] if attr['parameter'] in parameters else attr['parameter']+"_between"
75 default, vnfs = get_matching_vnfs(attr['resources'], vnf_list)
77 value = [vnf] if attr['parameter'] in parameters else [attr['customerLocationInfo'], vnf]
78 parameter_list.append({
79 attr['operator']: [attr['weight'], {parameter: value}]
82 optimization_policy_list.append({
83 content['objective']: {content['objectiveParameter']['operator']: parameter_list }
85 return optimization_policy_list
88 def get_matching_vnfs(resources, vnf_list, match_type="intersection"):
89 """Get a list of matching VNFs from the list of resources
91 :param vnf_list: List of vnfs to used in placement request
92 :param match_type: "intersection" or "all" or "any" (any => send all_vnfs if there is any intersection)
93 :return: List of matching VNFs
95 # Check if it is a default policy
96 default = True if resources == [] else False
97 resources_lcase = [x.lower() for x in resources] if not default else [x.lower() for x in vnf_list]
98 if match_type == "all": # don't bother with any comparisons
99 return default, resources if set(resources_lcase) <= set(vnf_list) else None
100 common_vnfs = set(vnf_list) & set(resources_lcase) if not default else set(vnf_list)
101 common_resources = [x for x in resources if x.lower() in common_vnfs] if not default else list(common_vnfs)
102 if match_type == "intersection": # specifically requested intersection
103 return default, list(common_resources)
104 return default, resources if common_vnfs else None # "any" match => all resources to be returned
107 def gen_policy_instance(vnf_list, resource_policy, match_type="intersection", rtype=None):
108 """Generate a list of policies
109 :param vnf_list: List of vnf's to used in placement request
110 :param resource_policy: policy for this specific resource
111 :param match_type: How to match the vnf_names with the vnf_list (intersection or "any")
112 intersection => return intersection; "any" implies return all vnf_names if intersection is not null
113 :param rtype: resource type (e.g. resourceRegionProperty or resourceInstanceProperty)
114 None => no controller information added to the policy specification to Conductor
115 :return: resource policy list in a format required by Conductor
117 resource_policy_list = []
118 related_policies = []
119 for policy in resource_policy:
120 pc = policy[list(policy.keys())[0]]
121 default, demands = get_matching_vnfs(pc['properties']['resources'], vnf_list, match_type=match_type)
122 resource = {pc['properties']['identity']: {'type': CONSTRAINT_TYPE_MAP.get(pc['type']), 'demands': demands}}
125 resource[pc['properties']['identity']]['properties'] = {'controller': pc[rtype]['controller'],
126 'request': json.loads(pc[rtype]['request'])}
127 if demands and len(demands) != 0:
128 # The default policy shall not override the specific policy that already appended
131 resource_repeated = True \
132 if {pc['properties']['identity']: {'type': CONSTRAINT_TYPE_MAP.get(pc['type']), 'demands': d}} \
133 in resource_policy_list else False
134 if resource_repeated:
137 resource_policy_list.append(
138 {pc['properties']['identity']: {'type': CONSTRAINT_TYPE_MAP.get(pc['type']), 'demands': d }})
139 policy[list(policy.keys())[0]]['properties']['resources'] = d
140 related_policies.append(policy)
141 # Need to override the default policies, here delete the outdated policy stored in the db
142 if resource in resource_policy_list:
143 for pc in related_policies:
144 if pc[list(pc.keys()[0])]['properties']['resources'] == resource:
145 related_policies.remove(pc)
146 resource_policy_list.remove(resource)
147 related_policies.append(policy)
148 resource_policy_list.append(resource)
150 return resource_policy_list, related_policies
153 def gen_resource_instance_policy(vnf_list, resource_instance_policy):
154 """Get policies governing resource instances in order to populate the Conductor API call"""
155 cur_policies, _ = gen_policy_instance(vnf_list, resource_instance_policy, rtype='resourceInstanceProperty')
159 def gen_resource_region_policy(vnf_list, resource_region_policy):
160 """Get policies governing resource region in order to populate the Conductor API call"""
161 cur_policies, _ = gen_policy_instance(vnf_list, resource_region_policy, rtype='resourceRegionProperty')
165 def gen_inventory_group_policy(vnf_list, inventory_group_policy):
166 """Get policies governing inventory group in order to populate the Conductor API call"""
167 cur_policies, _ = gen_policy_instance(vnf_list, inventory_group_policy, rtype=None)
171 def gen_reservation_policy(vnf_list, reservation_policy):
172 """Get policies governing resource instances in order to populate the Conductor API call"""
173 cur_policies, _ = gen_policy_instance(vnf_list, reservation_policy, rtype='instanceReservationProperty')
177 def gen_distance_to_location_policy(vnf_list, distance_to_location_policy):
178 """Get policies governing distance-to-location for VNFs in order to populate the Conductor API call"""
179 cur_policies, related_policies = gen_policy_instance(vnf_list, distance_to_location_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']['distanceProperties']
182 pcp_d = properties['distance']
183 p_new[p_main[list(p_main.keys())[0]]['properties']['identity']]['properties'] = {
184 'distance': pcp_d['operator'] + " " + pcp_d['value'].lower() + " " + pcp_d['unit'].lower(),
185 'location': properties['locationInfo']
190 def gen_attribute_policy(vnf_list, attribute_policy):
191 """Get policies governing attributes of VNFs in order to populate the Conductor API call"""
192 cur_policies, related_policies = gen_policy_instance(vnf_list, attribute_policy, rtype=None)
193 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
194 properties = p_main[list(p_main.keys())[0]]['properties']['attributeProperties']
195 attribute_mapping = policy_config_mapping['filtering_attributes'] # wanted attributes and mapping
196 p_new[p_main[list(p_main.keys())[0]]['properties']['identity']]['properties'] = {
197 'evaluate': dict((attribute_mapping[k], properties.get(k)
198 if k != "cloudRegion" else gen_cloud_region(properties))
199 for k in attribute_mapping.keys())
201 return cur_policies # cur_policies gets updated in place...
204 def gen_zone_policy(vnf_list, zone_policy):
205 """Get zone policies in order to populate the Conductor API call"""
206 cur_policies, related_policies = gen_policy_instance(vnf_list, zone_policy, match_type="all", rtype=None)
207 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
208 pmz = p_main[list(p_main.keys())[0]]['properties']['affinityProperties']
209 p_new[p_main[list(p_main.keys())[0]]['properties']['identity']]['properties'] = \
210 {'category': pmz['category'], 'qualifier': pmz['qualifier']}
214 def gen_capacity_policy(vnf_list, capacity_policy):
215 """Get zone policies in order to populate the Conductor API call"""
216 cur_policies, related_policies = gen_policy_instance(vnf_list, capacity_policy, rtype=None)
217 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
218 pmz = p_main[list(p_main.keys())[0]]['properties']['capacityProperty']
219 p_new[p_main[list(p_main.keys())[0]]['properties']['identity']]['properties'] = \
220 {"controller": pmz['controller'], 'request': json.loads(pmz['request'])}
224 def gen_hpa_policy(vnf_list, hpa_policy):
225 """Get zone policies in order to populate the Conductor API call"""
226 cur_policies, related_policies = gen_policy_instance(vnf_list, hpa_policy, rtype=None)
227 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
228 p_new[p_main[list(p_main.keys())[0]]['properties']['identity']]['properties'] = \
229 {'evaluate': p_main[list(p_main.keys())[0]]['properties']['flavorFeatures']}
233 def gen_threshold_policy(vnf_list, threshold_policy):
234 cur_policies, related_policies = gen_policy_instance(vnf_list, threshold_policy, rtype=None)
235 for p_new, p_main in zip(cur_policies, related_policies):
236 pmz = p_main[list(p_main.keys())[0]]['properties']['thresholdProperties']
237 p_new[p_main[list(p_main.keys())[0]]['properties']['identity']]['properties'] = {'evaluate': pmz}
241 def gen_aggregation_policy(vnf_list, cross_policy):
242 cur_policies, related_policies = gen_policy_instance(vnf_list, cross_policy, rtype=None)
243 for p_new, p_main in zip(cur_policies, related_policies):
244 pmz = p_main[list(p_main.keys())[0]]['properties']['aggregationProperties']
245 p_new[p_main[list(p_main.keys())[0]]['properties']['identity']]['properties'] = {'evaluate': pmz}
249 def get_augmented_policy_attributes(policy_property, demand):
250 """Get policy attributes and augment them using policy_config_mapping and demand information"""
251 attributes = copy.copy(policy_property['attributes'])
252 remapping = policy_config_mapping['remapping']
253 extra = dict((x, demand['resourceModelInfo'][remapping[x]]) for x in attributes if x in remapping)
254 attributes.update(extra)
258 def get_candidates_demands(demand):
259 """Get demands related to candidates; e.g. excluded/required"""
261 for k, v in policy_config_mapping['candidates'].items():
264 res[v] = [{'inventory_type': x['identifierType'], 'candidate_id': x['identifiers']} for x in demand[k]]
268 def get_policy_properties(demand, policies):
269 """Get policy_properties for cases where there is a match with the demand"""
270 for policy in policies:
271 policy_demands = set([x.lower() for x in policy[list(policy.keys())[0]]['properties']['resources']])
272 if policy_demands and demand['resourceModuleName'].lower() not in policy_demands:
273 continue # no match for this policy
274 elif policy_demands == set(): # Append resource name for default policy
275 policy[list(policy.keys())[0]]['properties'].update(resources=list(demand.get('resourceModuleName')))
276 for policy_property in policy[list(policy.keys())[0]]['properties']['vnfProperties']:
277 yield policy_property
280 def get_demand_properties(demand, policies):
281 """Get list demand properties objects (named tuples) from policy"""
282 demand_properties = []
283 for policy_property in get_policy_properties(demand, policies):
284 prop = dict(inventory_provider=policy_property['inventoryProvider'],
285 inventory_type=policy_property['inventoryType'],
286 service_type=demand.get('serviceResourceId', ''),
287 service_resource_id=demand.get('serviceResourceId', ''))
289 prop.update({'unique': policy_property['unique']} if 'unique' in policy_property and
290 policy_property['unique'] else {})
291 prop['filtering_attributes'] = dict()
292 if policy_property.get('attributes'):
293 for attr_key, attr_val in policy_property['attributes'].items():
294 update_converted_attribute(attr_key, attr_val, prop, 'filtering_attributes')
295 if policy_property.get('passthroughAttributes'):
296 prop['passthrough_attributes'] = dict()
297 for attr_key, attr_val in policy_property['passthroughAttributes'].items():
298 update_converted_attribute(attr_key, attr_val, prop, 'passthrough_attributes')
300 prop['filtering_attributes'].update({'global-customer-id': policy_property['customerId']}
301 if 'customerId' in policy_property and policy_property['customerId'] else {})
302 prop['filtering_attributes'].update({'model-invariant-id': demand['resourceModelInfo']['modelInvariantId']}
303 if 'modelInvariantId' in demand['resourceModelInfo'] and demand['resourceModelInfo']['modelInvariantId'] else {})
304 prop['filtering_attributes'].update({'model-version-id': demand['resourceModelInfo']['modelVersionId']}
305 if 'modelVersionId' in demand['resourceModelInfo'] and demand['resourceModelInfo']['modelVersionId'] else {})
306 prop['filtering_attributes'].update({'equipment-role': policy_property['equipmentRole']}
307 if 'equipmentRole' in policy_property and policy_property['equipmentRole'] else {})
309 prop.update(get_candidates_demands(demand))
310 demand_properties.append(prop)
311 return demand_properties
314 def update_converted_attribute(attr_key, attr_val, properties, attribute_type):
316 Updates dictonary of attributes with one specified in the arguments.
317 Automatically translates key namr from camelCase to hyphens
318 :param attribute_type: attribute section name
319 :param attr_key: key of the attribute
320 :param attr_val: value of the attribute
321 :param properties: dictionary with attributes to update
325 remapping = policy_config_mapping[attribute_type]
326 if remapping.get(attr_key):
327 key_value = remapping.get(attr_key)
329 key_value = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', attr_key)
330 key_value = re.sub('([a-z0-9])([A-Z])', r'\1-\2', key_value).lower()
331 properties[attribute_type].update({key_value: attr_val})
334 def gen_demands(demands, vnf_policies):
335 """Generate list of demands based on request and VNF policies
336 :param demands: A List of demands
337 :param vnf_policies: Policies associated with demand resources
338 (e.g. from grouped_policies['vnfPolicy'])
339 :return: list of demand parameters to populate the Conductor API call
341 demand_dictionary = {}
342 for demand in demands:
343 prop = get_demand_properties(demand, vnf_policies)
345 demand_dictionary.update({demand['resourceModuleName']: prop})
346 return demand_dictionary
349 def gen_cloud_region(property):
350 prop = {"cloud_region_attributes": dict()}
351 if 'cloudRegion' in property:
352 for k,v in property['cloudRegion'].items():
353 update_converted_attribute(k, v, prop, 'cloud_region_attributes')
354 return prop["cloud_region_attributes"]