9acfa2ad85abeba8d50289680ff3eb609dcdbe23
[optf/osdf.git] / osdf / adapters / policy / utils.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
21 from collections import defaultdict
22
23 from osdf.utils.programming_utils import dot_notation, list_flatten
24
25
26 def group_policies(flat_policies):
27     """Filter policies using the following steps:
28     1. Apply prioritization among the policies that are sharing the same policy type and resource type
29     2. Remove redundant policies that may applicable across different types of resource
30     3. Filter policies based on type and return
31     :param flat_policies: list of flat policies
32     :return: Filtered policies
33     """
34     filtered_policies = defaultdict(list)
35     policy_name = []
36     policies = [x for x in flat_policies if x['content'].get('policy_type')]  # drop ones without 'policy_type'
37     policy_types = set([x['content'].get('policyType') for x in policies])
38     aggregated_policies = dict((x, defaultdict(list)) for x in policy_types)
39
40     for policy in policies:
41         policy_type = policy['content'].get('policyType')
42         for resource in policy['content'].get('resourceInstanceType', []):
43             aggregated_policies[policy_type][resource].append(policy)
44
45     for policy_type in aggregated_policies:
46         for resource in aggregated_policies[policy_type]:
47             if aggregated_policies[policy_type][resource]:
48                 aggregated_policies[policy_type][resource].sort(key=lambda x: x['priority'], reverse=True)
49                 prioritized_policy = aggregated_policies[policy_type][resource][0]
50                 if prioritized_policy['policyName'] not in policy_name:
51                     # TODO: Check logic here... should policy appear only once across all groups?
52                     filtered_policies[prioritized_policy['content']['policyType']].append(prioritized_policy)
53                     policy_name.append(prioritized_policy['policyName'])
54     return filtered_policies
55
56
57 def policy_name_as_regex(policy_name):
58     """Get the correct policy name as a regex
59     (e.g. OOF_HAS_vCPE.cloudAttributePolicy ends up in policy as OOF_HAS_vCPE.Config_MS_cloudAttributePolicy.1.xml
60     So, for now, we query it as OOF_HAS_vCPE..*aicAttributePolicy.*)
61     :param policy_name: Example: OOF_HAS_vCPE.aicAttributePolicy
62     :return: regexp for policy: Example: OOF_HAS_vCPE..*aicAttributePolicy.*
63     """
64     p = policy_name.partition('.')
65     return p[0] + p[1] + ".*" + p[2] + ".*"
66
67
68 def retrieve_node(req_json, reference):
69     """
70     Get the child node(s) from the dot-notation [reference] and parent [req_json].
71     For placement and other requests, there are encoded JSONs inside the request or policy,
72     so we need to expand it and then do a search over the parent plus expanded JSON.
73     """
74     req_json_copy = copy.deepcopy(req_json)  # since we expand the JSON in place, we work on a copy
75     if 'orderInfo' in req_json_copy['placementInfo']:
76         req_json_copy['placementInfo']['orderInfo'] = json.loads(req_json_copy['placementInfo']['orderInfo'])
77     info = dot_notation(req_json_copy, reference)
78     return list_flatten(info) if isinstance(info, list) else info