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 # -------------------------------------------------------------------------
22 from osdf.utils.data_conversion import text_to_symbol
24 policy_config_mapping = yaml.load(open('config/has_config.yaml')).get('policy_config_mapping')
27 def gen_optimization_policy(vnf_list, optimization_policy):
28 """Generate optimization policy details to pass to Conductor
29 :param vnf_list: List of vnf's to used in placement request
30 :param optimization_policy: optimization objective policy information provided in the incoming request
31 :return: List of optimization objective policies in a format required by Conductor
33 optimization_policy_list = []
34 for policy in optimization_policy:
35 content = policy['content']
38 for attr in content['objectiveParameter']['parameterAttributes']:
39 parameter = attr['parameter'] if attr['parameter'] == "cloud_version" else attr['parameter']+"_between"
40 vnfs = get_matching_vnfs(attr['resources'], vnf_list)
42 value = [vnf] if attr['parameter'] == "cloud_version" else [attr['customerLocationInfo'], vnf]
43 parameter_list.append({
44 attr['operator']: [attr['weight'], {parameter: value}]
47 optimization_policy_list.append({
48 content['objective']: {content['objectiveParameter']['operator']: parameter_list }
50 return optimization_policy_list
53 def get_matching_vnfs(resources, vnf_list, match_type="intersection"):
54 """Get a list of matching VNFs from the list of resources
56 :param vnf_list: List of vnfs to used in placement request
57 :param match_type: "intersection" or "all" or "any" (any => send all_vnfs if there is any intersection)
58 :return: List of matching VNFs
60 if match_type == "all": # don't bother with any comparisons
61 return resources if set(resources) <= set(vnf_list) else None
62 common_vnfs = set(vnf_list) & set(resources)
63 if match_type == "intersection": # specifically requested intersection
64 return list(common_vnfs)
65 return resources if common_vnfs else None # "any" match => all resources to be returned
68 def gen_policy_instance(vnf_list, resource_policy, match_type="intersection", rtype=None):
69 """Generate a list of policies
70 :param vnf_list: List of vnf's to used in placement request
71 :param resource_policy: policy for this specific resource
72 :param match_type: How to match the vnf_names with the vnf_list (intersection or "any")
73 intersection => return intersection; "any" implies return all vnf_names if intersection is not null
74 :param rtype: resource type (e.g. resourceRegionProperty or resourceInstanceProperty)
75 None => no controller information added to the policy specification to Conductor
76 :return: resource policy list in a format required by Conductor
78 resource_policy_list = []
80 for policy in resource_policy:
81 pc = policy['content']
82 demands = get_matching_vnfs(pc['resources'], vnf_list, match_type=match_type)
83 resource = {pc['identity']: {'type': pc['policyType'], 'demands': demands}}
86 resource[pc['identity']]['properties'] = {'controller': pc[rtype]['controller'],
87 'request': json.loads(pc[rtype]['request'])}
88 if demands and len(demands) != 0:
89 resource_policy_list.append(resource)
90 related_policies.append(policy)
91 return resource_policy_list, related_policies
94 def gen_resource_instance_policy(vnf_list, resource_instance_policy):
95 """Get policies governing resource instances in order to populate the Conductor API call"""
96 cur_policies, _ = gen_policy_instance(vnf_list, resource_instance_policy, rtype='resourceInstanceProperty')
100 def gen_resource_region_policy(vnf_list, resource_region_policy):
101 """Get policies governing resource region in order to populate the Conductor API call"""
102 cur_policies, _ = gen_policy_instance(vnf_list, resource_region_policy, rtype='resourceRegionProperty')
106 def gen_inventory_group_policy(vnf_list, inventory_group_policy):
107 """Get policies governing inventory group in order to populate the Conductor API call"""
108 cur_policies, _ = gen_policy_instance(vnf_list, inventory_group_policy, rtype=None)
112 def gen_reservation_policy(vnf_list, reservation_policy):
113 """Get policies governing resource instances in order to populate the Conductor API call"""
114 cur_policies, _ = gen_policy_instance(vnf_list, reservation_policy, rtype='instanceReservationProperty')
118 def gen_distance_to_location_policy(vnf_list, distance_to_location_policy):
119 """Get policies governing distance-to-location for VNFs in order to populate the Conductor API call"""
120 cur_policies, related_policies = gen_policy_instance(vnf_list, distance_to_location_policy, rtype=None)
121 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
122 properties = p_main['content']['distanceProperties']
123 pcp_d = properties['distance']
124 p_new[p_main['content']['identity']]['properties'] = {
125 'distance': pcp_d['operator'] + " " + pcp_d['value'].lower() + " " + pcp_d['unit'].lower(),
126 'location': properties['locationInfo']
131 def gen_attribute_policy(vnf_list, attribute_policy):
132 """Get policies governing attributes of VNFs in order to populate the Conductor API call"""
133 cur_policies, related_policies = gen_policy_instance(vnf_list, attribute_policy, rtype=None)
134 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
135 properties = p_main['content']['cloudAttributeProperty']
136 attribute_mapping = policy_config_mapping['attributes'] # wanted attributes and mapping
137 p_new[p_main['content']['identity']]['properties'] = {
138 'evaluate': dict((k, properties.get(attribute_mapping.get(k))) for k in attribute_mapping.keys())
140 return cur_policies # cur_policies gets updated in place...
143 def gen_zone_policy(vnf_list, zone_policy):
144 """Get zone policies in order to populate the Conductor API call"""
145 cur_policies, related_policies = gen_policy_instance(vnf_list, zone_policy, match_type="all", rtype=None)
146 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
147 pmz = p_main['content']['affinityProperty']
148 p_new[p_main['content']['identity']]['properties'] = {'category': pmz['category'], 'qualifier': pmz['qualifier']}
152 def gen_capacity_policy(vnf_list, capacity_policy):
153 """Get zone policies in order to populate the Conductor API call"""
154 cur_policies, related_policies = gen_policy_instance(vnf_list, capacity_policy, rtype=None)
155 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
156 pmz = p_main['content']['capacityProperty']
157 p_new[p_main['content']['identity']]['properties'] = \
158 {"controller": pmz['controller'], 'request': json.loads(pmz['request'])}
162 def gen_hpa_policy(vnf_list, hpa_policy):
163 """Get zone policies in order to populate the Conductor API call"""
164 cur_policies, related_policies = gen_policy_instance(vnf_list, hpa_policy, rtype=None)
165 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
166 p_new[p_main['content']['identity']]['properties'] = {'evaluate': p_main['content']['flavorFeatures']}
170 def get_augmented_policy_attributes(policy_property, demand):
171 """Get policy attributes and augment them using policy_config_mapping and demand information"""
172 attributes = copy.copy(policy_property['attributes'])
173 remapping = policy_config_mapping['remapping']
174 extra = dict((x, demand['resourceModelInfo'][remapping[x]]) for x in attributes if x in remapping)
175 attributes.update(extra)
179 def get_candidates_demands(demand):
180 """Get demands related to candidates; e.g. excluded/required"""
182 for k, v in policy_config_mapping['candidates'].items():
185 res[v] = [{'inventory_type': x['candidateType'], 'candidate_id': x['candidates']} for x in demand[k]]
189 def get_policy_properties(demand, policies):
190 """Get policy_properties for cases where there is a match with the demand"""
191 for policy in policies:
192 if demand['resourceModuleName'] not in set(policy['content'].get('resources', [])):
193 continue # no match for this policy
194 for policy_property in policy['content']['vnfProperties']:
195 yield policy_property
198 def get_demand_properties(demand, policies):
199 """Get list demand properties objects (named tuples) from policy"""
200 demand_properties = []
201 for policy_property in get_policy_properties(demand, policies):
202 prop = dict(inventory_provider=policy_property['inventoryProvider'],
203 inventory_type=policy_property['inventoryType'],
204 service_resource_id=demand['serviceResourceId'])
205 if 'attributes' in policy_property:
206 prop['attributes'] = get_augmented_policy_attributes(policy_property, demand)
207 for k1, v1, k2, v2 in policy_config_mapping['extra_fields']:
210 prop.update(get_candidates_demands(demand)) # for excluded and partial-rehoming cases
211 demand_properties.append(prop)
212 return demand_properties
215 def gen_demands(req_json, vnf_policies):
216 """Generate list of demands based on request and VNF policies
217 :param req_json: Request object from the client (e.g. MSO)
218 :param vnf_policies: Policies associated with demand resources (e.g. from grouped_policies['vnfPolicy'])
219 :return: list of demand parameters to populate the Conductor API call
221 demand_dictionary = {}
222 for demand in req_json['placementInfo']['placementDemands']:
223 demand_dictionary.update(
224 {demand['resourceModuleName']: get_demand_properties(demand, vnf_policies)})
225 return demand_dictionary