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_vnf(resource, vnf_list):
61 def get_matching_vnfs(resources, vnf_list, match_type="intersection"):
62 """Get a list of matching VNFs from the list of resources
64 :param vnf_list: List of vnfs to used in placement request
65 :param match_type: "intersection" or "all" or "any" (any => send all_vnfs if there is any intersection)
66 :return: List of matching VNFs
68 if match_type == "all": # don't bother with any comparisons
69 return resources if set(resources) <= set(vnf_list) else None
70 common_vnfs = set(vnf_list) & set(resources)
71 if match_type == "intersection": # specifically requested intersection
72 return list(common_vnfs)
73 return resources if common_vnfs else None # "any" match => all resources to be returned
76 def gen_policy_instance(vnf_list, resource_policy, match_type="intersection", rtype=None):
77 """Generate a list of policies
78 :param vnf_list: List of vnf's to used in placement request
79 :param resource_policy: policy for this specific resource
80 :param match_type: How to match the vnf_names with the vnf_list (intersection or "any")
81 intersection => return intersection; "any" implies return all vnf_names if intersection is not null
82 :param rtype: resource type (e.g. resourceRegionProperty or resourceInstanceProperty)
83 None => no controller information added to the policy specification to Conductor
84 :return: resource policy list in a format required by Conductor
86 resource_policy_list = []
88 for policy in resource_policy:
89 pc = policy['content']
90 demands = get_matching_vnfs(pc['resources'], vnf_list, match_type=match_type)
91 resource = {pc['identity']: {'type': pc['policyType'], 'demands': demands}}
94 resource[pc['identity']]['properties'] = {'controller': pc[rtype]['controller'],
95 'request': json.loads(pc[rtype]['request'])}
96 if demands and len(demands) != 0:
97 resource_policy_list.append(resource)
98 related_policies.append(policy)
99 return resource_policy_list, related_policies
102 def gen_resource_instance_policy(vnf_list, resource_instance_policy):
103 """Get policies governing resource instances in order to populate the Conductor API call"""
104 cur_policies, _ = gen_policy_instance(vnf_list, resource_instance_policy, rtype='resourceInstanceProperty')
108 def gen_resource_region_policy(vnf_list, resource_region_policy):
109 """Get policies governing resource region in order to populate the Conductor API call"""
110 cur_policies, _ = gen_policy_instance(vnf_list, resource_region_policy, rtype='resourceRegionProperty')
114 def gen_inventory_group_policy(vnf_list, inventory_group_policy):
115 """Get policies governing inventory group in order to populate the Conductor API call"""
116 cur_policies, _ = gen_policy_instance(vnf_list, inventory_group_policy, rtype=None)
120 def gen_reservation_policy(vnf_list, reservation_policy):
121 """Get policies governing resource instances in order to populate the Conductor API call"""
122 cur_policies, _ = gen_policy_instance(vnf_list, reservation_policy, rtype='instanceReservationProperty')
126 def gen_distance_to_location_policy(vnf_list, distance_to_location_policy):
127 """Get policies governing distance-to-location for VNFs in order to populate the Conductor API call"""
128 cur_policies, related_policies = gen_policy_instance(vnf_list, distance_to_location_policy, rtype=None)
129 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
130 properties = p_main['content']['distanceProperties']
131 pcp_d = properties['distance']
132 p_new[p_main['content']['identity']]['properties'] = {
133 'distance': pcp_d['operator'] + " " + pcp_d['value'].lower() + " " + pcp_d['unit'].lower(),
134 'location': properties['locationInfo']
139 def gen_attribute_policy(vnf_list, attribute_policy):
140 """Get policies governing attributes of VNFs in order to populate the Conductor API call"""
141 cur_policies, related_policies = gen_policy_instance(vnf_list, attribute_policy, rtype=None)
142 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
143 properties = p_main['content']['cloudAttributeProperty']
144 attribute_mapping = policy_config_mapping['attributes'] # wanted attributes and mapping
145 p_new[p_main['content']['identity']]['properties'] = {
146 'evaluate': dict((k, properties.get(attribute_mapping.get(k))) for k in attribute_mapping.keys())
148 return cur_policies # cur_policies gets updated in place...
151 def gen_zone_policy(vnf_list, zone_policy):
152 """Get zone policies in order to populate the Conductor API call"""
153 cur_policies, related_policies = gen_policy_instance(vnf_list, zone_policy, match_type="all", rtype=None)
154 for p_new, p_main in zip(cur_policies, related_policies): # add additional fields to each policy
155 pmz = p_main['content']['affinityProperty']
156 p_new[p_main['content']['identity']]['properties'] = {'category': pmz['category'], 'qualifier': pmz['qualifier']}
160 def get_augmented_policy_attributes(policy_property, demand):
161 """Get policy attributes and augment them using policy_config_mapping and demand information"""
162 attributes = copy.copy(policy_property['attributes'])
163 remapping = policy_config_mapping['remapping']
164 extra = dict((x, demand['resourceModelInfo'][remapping[x]]) for x in attributes if x in remapping)
165 attributes.update(extra)
169 def get_candidates_demands(demand):
170 """Get demands related to candidates; e.g. excluded/required"""
172 for k, v in policy_config_mapping['candidates'].items():
175 res[v] = [{'inventory_type': x['candidateType'], 'candidate_id': x['candidates']} for x in demand[k]]
179 def get_policy_properties(demand, policies):
180 """Get policy_properties for cases where there is a match with the demand"""
181 for policy in policies:
182 if demand['resourceModuleName'] not in set(policy['content'].get('resources', [])):
183 continue # no match for this policy
184 for policy_property in policy['content']['vnfProperties']:
185 yield policy_property
188 def get_demand_properties(demand, policies):
189 """Get list demand properties objects (named tuples) from policy"""
190 demand_properties = []
191 for policy_property in get_policy_properties(demand, policies):
192 prop = dict(inventory_provider=policy_property['inventoryProvider'],
193 inventory_type=policy_property['inventoryType'],
194 service_resource_id=demand['serviceResourceId'])
195 if 'attributes' in policy_property:
196 prop['attributes'] = get_augmented_policy_attributes(policy_property, demand)
197 for k1, v1, k2, v2 in policy_config_mapping['extra_fields']:
200 prop.update(get_candidates_demands(demand)) # for excluded and partial-rehoming cases
201 demand_properties.append(prop)
202 return demand_properties
205 def gen_demands(req_json, vnf_policies):
206 """Generate list of demands based on request and VNF policies
207 :param req_json: Request object from the client (e.g. MSO)
208 :param vnf_policies: Policies associated with demand resources (e.g. from grouped_policies['vnfPolicy'])
209 :return: list of demand parameters to populate the Conductor API call
211 demand_dictionary = {}
212 for demand in req_json['placementInfo']['placementDemands']:
213 demand_dictionary.update(
214 {demand['resourceModuleName']: get_demand_properties(demand, vnf_policies)})
215 return demand_dictionary