Re-org folders, onboard test folder, test config
[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
19 from collections import defaultdict
20
21
22 def group_policies(flat_policies):
23     """Filter policies using the following steps:
24     1. Apply prioritization among the policies that are sharing the same policy type and resource type
25     2. Remove redundant policies that may applicable across different types of resource
26     3. Filter policies based on type and return
27     :param flat_policies: list of flat policies
28     :return: Filtered policies
29     """
30     aggregated_policies = {}
31     filter_policies = defaultdict(list)
32     policy_name = []
33     for policy in flat_policies:
34         policy_type = policy['content']['type']
35         if policy_type not in aggregated_policies:
36             aggregated_policies[policy_type] = defaultdict(list)
37         for resource in policy['content']['policyScope']['resourceInstanceType']:
38             aggregated_policies[policy_type][resource].append(policy)
39     for policy_type in aggregated_policies:
40         for resource in aggregated_policies[policy_type]:
41             if len(aggregated_policies[policy_type][resource]) > 0:
42                 aggregated_policies[policy_type][resource].sort(key=lambda x: x['priority'], reverse=True)
43                 policy = aggregated_policies[policy_type][resource][0]
44                 if policy['policyName'] not in policy_name:
45                     filter_policies[policy['content']['type']].append(policy)
46                     policy_name.append(policy['policyName'])
47     return filter_policies
48
49
50 def _regex_policy_name(policy_name):
51     """Get the correct policy name as a regex
52     (e.g. OOF_HAS_vCPE.cloudAttributePolicy ends up in policy as OOF_HAS_vCPE.Config_MS_cloudAttributePolicy.1.xml
53     So, for now, we query it as OOF_HAS_vCPE..*aicAttributePolicy.*)
54     :param policy_name: Example: OOF_HAS_vCPE.aicAttributePolicy
55     :return: regexp for policy: Example: OOF_HAS_vCPE..*aicAttributePolicy.*
56     """
57     p = policy_name.partition('.')
58     return p[0] + p[1] + ".*" + p[2] + ".*"