1 # -------------------------------------------------------------------------
2 # Copyright (c) 2015-2017 AT&T Intellectual Property
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
16 # -------------------------------------------------------------------------
23 from osdf.utils.data_conversion import text_to_symbol
24 from osdf.utils.programming_utils import dot_notation
26 policy_config_mapping = yaml.load(open('config/has_config.yaml')).get('policy_config_mapping')
29 def get_opt_query_data(req_json, policies):
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.
37 if 'requestParameters' in req_json["placementInfo"]:
38 req_params = req_json["placementInfo"]["requestParameters"]
39 for policy in policies:
40 for queryProp in policy['content']['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})
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
54 optimization_policy_list = []
55 for policy in optimization_policy:
56 content = policy['content']
58 parameters = ["cloud_version", "hpa_score"]
60 for attr in content['objectiveParameter']['parameterAttributes']:
61 parameter = attr['parameter'] if attr['parameter'] in parameters else attr['parameter']+"_between"
62 vnfs = get_matching_vnfs(attr['resources'], vnf_list)
64 value = [vnf] if attr['parameter'] in parameters else [attr['customerLocationInfo'], vnf]
65 parameter_list.append({
66 attr['operator']: [attr['weight'], {parameter: value}]
69 optimization_policy_list.append({
70 content['objective']: {content['objectiveParameter']['operator']: parameter_list }
72 return optimization_policy_list
75 def get_matching_vnfs(resources, vnf_list, match_type="intersection"):
76 """Get a list of matching VNFs from the list of 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
82 resources_lcase = [x.lower() for x in resources]
83 if match_type == "all": # don't bother with any comparisons
84 return resources if set(resources_lcase) <= set(vnf_list) else None
85 common_vnfs = set(vnf_list) & set(resources_lcase)
86 common_resources = [x for x in resources if x.lower() in common_vnfs]
87 if match_type == "intersection": # specifically requested intersection
88 return list(common_resources)
89 return resources if common_vnfs else None # "any" match => all resources to be returned
92 def gen_policy_instance(vnf_list, resource_policy, match_type="intersection", rtype=None):
93 """Generate a list of policies
94 :param vnf_list: List of vnf's to used in placement request
95 :param resource_policy: policy for this specific resource
96 :param match_type: How to match the vnf_names with the vnf_list (intersection or "any")
97 intersection => return intersection; "any" implies return all vnf_names if intersection is not null
98 :param rtype: resource type (e.g. resourceRegionProperty or resourceInstanceProperty)
99 None => no controller information added to the policy specification to Conductor
100 :return: resource policy list in a format required by Conductor
102 resource_policy_list = []
103 related_policies = []
104 for policy in resource_policy:
105 pc = policy['content']
106 demands = get_matching_vnfs(pc['resources'], vnf_list, match_type=match_type)
107 resource = {pc['identity']: {'type': pc['policyType'], 'demands': demands}}
110 resource[pc['identity']]['properties'] = {'controller': pc[rtype]['controller'],
111 'request': json.loads(pc[rtype]['request'])}
112 if demands and len(demands) != 0:
113 resource_policy_list.append(resource)
114 related_policies.append(policy)
115 return resource_policy_list, related_policies
118 def gen_resource_instance_policy(vnf_list, resource_instance_policy):
119 """Get policies governing resource instances in order to populate the Conductor API call"""
120 cur_policies, _ = gen_policy_instance(vnf_list, resource_instance_policy, rtype='resourceInstanceProperty')
124 def gen_resource_region_policy(vnf_list, resource_region_policy):
125 """Get policies governing resource region in order to populate the Conductor API call"""
126 cur_policies, _ = gen_policy_instance(vnf_list, resource_region_policy, rtype='resourceRegionProperty')
130 def gen_inventory_group_policy(vnf_list, inventory_group_policy):
131 """Get policies governing inventory group in order to populate the Conductor API call"""
132 cur_policies, _ = gen_policy_instance(vnf_list, inventory_group_policy, rtype=None)
136 def gen_reservation_policy(vnf_list, reservation_policy):
137 """Get policies governing resource instances in order to populate the Conductor API call"""
138 cur_policies, _ = gen_policy_instance(vnf_list, reservation_policy, rtype='instanceReservationProperty')
142 def gen_distance_to_location_policy(vnf_list, distance_to_location_policy):
143 """Get policies governing distance-to-location for VNFs in order to populate the Conductor API call"""
144 cur_policies, related_policies = gen_policy_instance(vnf_list, distance_to_location_policy, rtype=None)
145 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
146 properties = p_main['content']['distanceProperties']
147 pcp_d = properties['distance']
148 p_new[p_main['content']['identity']]['properties'] = {
149 'distance': pcp_d['operator'] + " " + pcp_d['value'].lower() + " " + pcp_d['unit'].lower(),
150 'location': properties['locationInfo']
155 def gen_attribute_policy(vnf_list, attribute_policy):
156 """Get policies governing attributes of VNFs in order to populate the Conductor API call"""
157 cur_policies, related_policies = gen_policy_instance(vnf_list, attribute_policy, rtype=None)
158 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
159 properties = p_main['content']['cloudAttributeProperty']
160 attribute_mapping = policy_config_mapping['attributes'] # wanted attributes and mapping
161 p_new[p_main['content']['identity']]['properties'] = {
162 'evaluate': dict((k, properties.get(attribute_mapping.get(k))) for k in attribute_mapping.keys())
164 return cur_policies # cur_policies gets updated in place...
167 def gen_zone_policy(vnf_list, zone_policy):
168 """Get zone policies in order to populate the Conductor API call"""
169 cur_policies, related_policies = gen_policy_instance(vnf_list, zone_policy, match_type="all", rtype=None)
170 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
171 pmz = p_main['content']['affinityProperty']
172 p_new[p_main['content']['identity']]['properties'] = {'category': pmz['category'], 'qualifier': pmz['qualifier']}
176 def gen_capacity_policy(vnf_list, capacity_policy):
177 """Get zone policies in order to populate the Conductor API call"""
178 cur_policies, related_policies = gen_policy_instance(vnf_list, capacity_policy, rtype=None)
179 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
180 pmz = p_main['content']['capacityProperty']
181 p_new[p_main['content']['identity']]['properties'] = \
182 {"controller": pmz['controller'], 'request': json.loads(pmz['request'])}
186 def gen_hpa_policy(vnf_list, hpa_policy):
187 """Get zone policies in order to populate the Conductor API call"""
188 cur_policies, related_policies = gen_policy_instance(vnf_list, hpa_policy, rtype=None)
189 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
190 p_new[p_main['content']['identity']]['properties'] = {'evaluate': p_main['content']['flavorFeatures']}
194 def get_augmented_policy_attributes(policy_property, demand):
195 """Get policy attributes and augment them using policy_config_mapping and demand information"""
196 attributes = copy.copy(policy_property['attributes'])
197 remapping = policy_config_mapping['remapping']
198 extra = dict((x, demand['resourceModelInfo'][remapping[x]]) for x in attributes if x in remapping)
199 attributes.update(extra)
203 def get_candidates_demands(demand):
204 """Get demands related to candidates; e.g. excluded/required"""
206 for k, v in policy_config_mapping['candidates'].items():
209 res[v] = [{'inventory_type': x['identifierType'], 'candidate_id': x['identifiers']} for x in demand[k]]
213 def get_policy_properties(demand, policies):
214 """Get policy_properties for cases where there is a match with the demand"""
215 for policy in policies:
216 policy_demands = set([x.lower() for x in policy['content'].get('resources', [])])
217 if demand['resourceModuleName'].lower() not in policy_demands:
218 continue # no match for this policy
219 for policy_property in policy['content']['vnfProperties']:
220 yield policy_property
223 def get_demand_properties(demand, policies):
224 """Get list demand properties objects (named tuples) from policy"""
225 demand_properties = []
226 for policy_property in get_policy_properties(demand, policies):
227 prop = dict(inventory_provider=policy_property['inventoryProvider'],
228 inventory_type=policy_property['inventoryType'],
229 service_type=demand['serviceResourceId'],
230 service_resource_id=demand['serviceResourceId'])
232 prop.update({'unique': demand['unique']} if demand.get('unique') else {})
233 prop['attributes'] = dict()
234 prop['attributes'].update({'global-customer-id': policy_property['customerId']}
235 if policy_property['customerId'] else {})
236 prop['attributes'].update({'model-invariant-id': demand['resourceModelInfo']['modelInvariantId']}
237 if demand['resourceModelInfo']['modelInvariantId'] else {})
238 prop['attributes'].update({'model-version-id': demand['resourceModelInfo']['modelVersionId']}
239 if demand['resourceModelInfo']['modelVersionId'] else {})
240 prop['attributes'].update({'equipment-role': policy_property['equipmentRole']}
241 if policy_property['equipmentRole'] else {})
243 if policy_property.get('attributes'):
244 for attr_key, attr_val in policy_property['attributes'].items():
245 update_converted_attribute(attr_key, attr_val, prop)
247 prop.update(get_candidates_demands(demand))
248 demand_properties.append(prop)
249 return demand_properties
252 def update_converted_attribute(attr_key, attr_val, properties):
254 Updates dictonary of attributes with one specified in the arguments.
255 Automatically translates key namr from camelCase to hyphens
256 :param attr_key: key of the attribute
257 :param attr_val: value of the attribute
258 :param properties: dictionary with attributes to update
262 remapping = policy_config_mapping['attributes']
263 if remapping.get(attr_key):
264 key_value = remapping.get(attr_key)
266 key_value = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', attr_key)
267 key_value = re.sub('([a-z0-9])([A-Z])', r'\1-\2', key_value).lower()
268 properties['attributes'].update({key_value: attr_val})
271 def gen_demands(req_json, vnf_policies):
272 """Generate list of demands based on request and VNF policies
273 :param req_json: Request object from the client (e.g. MSO)
274 :param vnf_policies: Policies associated with demand resources (e.g. from grouped_policies['vnfPolicy'])
275 :return: list of demand parameters to populate the Conductor API call
277 demand_dictionary = {}
278 for demand in req_json['placementInfo']['placementDemands']:
279 prop = get_demand_properties(demand, vnf_policies)
281 demand_dictionary.update({demand['resourceModuleName']: prop})
282 return demand_dictionary