New policies and required code changes
[optf/osdf.git] / osdf / adapters / policy / interface.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 import base64
20 import itertools
21 import json
22
23
24 from requests import RequestException
25 from osdf.operation.exceptions import BusinessException
26 from osdf.adapters.local_data.local_policies import get_local_policies
27 from osdf.adapters.policy.utils import _regex_policy_name
28 from osdf.config.base import osdf_config
29 from osdf.logging.osdf_logging import audit_log, MH, metrics_log, error_log, debug_log
30 from osdf.utils.interfaces import RestClient
31 from osdf.optimizers.placementopt.conductor.api_builder import retrieve_node
32 # from osdf.utils import data_mapping
33
34
35 def get_by_name(rest_client, policy_name_list, wildcards=True):
36     policy_list = []
37     for policy_name in policy_name_list:
38         try:
39             query_name = policy_name
40             if wildcards:
41                 query_name = _regex_policy_name(query_name)
42             policy_list.append(rest_client.request(json={"policyName": query_name}))
43         except RequestException as err:
44             audit_log.warn("Error in fetching policy: " + policy_name)
45             raise BusinessException("Cannot fetch policy {}: ".format(policy_name), err)
46     return policy_list
47
48
49 def get_subscriber_name(req, pmain):
50     subs_name = retrieve_node(req, pmain['subscriber_name'])
51     if subs_name is None:
52         return "DEFAULT"
53     else:
54         subs_name_uc = subs_name.upper()
55         if subs_name_uc in ("DEFAULT", "NULL", ""):
56             subs_name = "DEFAULT"
57     return subs_name
58
59
60 def get_subscriber_role(rest_client, req, pmain, service_name, scope):
61     """Make a request to policy and return subscriberRole
62     :param rest_client: rest client to make call
63     :param req: request object from MSO
64     :param pmain: main config that will have policy path information
65     :param service_name: the type of service to call: e.g. "vCPE
66     :param scope: the scope of policy to call: e.g. "OOF_HAS_vCPE".
67     :return: subscriberRole and provStatus retrieved from Subscriber policy
68     """
69     subscriber_role = "DEFAULT"
70     prov_status = []
71     subs_name = get_subscriber_name(req, pmain)
72     if subs_name == "DEFAULT":
73         return subscriber_role, prov_status
74     
75     policy_subs = pmain['policy_subscriber']
76     policy_scope = {"policyName": "{}.*".format(scope),
77                     "configAttributes": {
78                         "serviceType": "{}".format(service_name),
79                         "service": "{}".format(policy_subs)}
80                     }
81     policy_list = []
82     try:
83         policy_list.append(rest_client.request(json=policy_scope))
84     except RequestException as err:
85         audit_log.warn("Error in fetching policy for {}: ".format(policy_subs))
86         return subscriber_role, prov_status
87             
88     formatted_policies = []
89     for x in itertools.chain(*policy_list):
90         if x['config'] is None:
91             raise BusinessException("Config not found for policy with name %s" % x['policyName'])
92         else:
93             formatted_policies.append(json.loads(x['config']))
94     
95     for policy in formatted_policies:
96         property_list = policy['content']['property']
97         for prop in property_list:
98             if subs_name in prop['subscriberName']:
99                 subs_role_list = prop['subscriberRole']
100                 prov_status = prop['provStatus']
101                 if isinstance(subs_role_list, list): # as list is returned
102                     return subs_role_list[0], prov_status
103     return subscriber_role, prov_status
104     
105
106 def get_by_scope(rest_client, req, config_local, type_service):
107     policy_list = []
108     pmain = config_local['policy_info'][type_service]
109     pscope = pmain['policy_scope']
110     
111     model_name = retrieve_node(req, pscope['service_name'])
112     service_name = model_name
113
114     scope = pscope['scope_{}'.format(service_name.lower())]
115     subscriber_role, prov_status = get_subscriber_role(rest_client, req, pmain, service_name, scope)
116     policy_type_list = pmain['policy_type_{}'.format(service_name.lower())]
117     for policy_type in policy_type_list:
118         policy_scope = {"policyName": "{}.*".format(scope),
119                         "configAttributes": {
120                             "serviceType": "{}".format(service_name),
121                             "service": "{}".format(policy_type),
122                             "subscriberRole": "{}".format(subscriber_role)}
123                         }
124         policy_list.append(rest_client.request(json=policy_scope))
125     return policy_list, prov_status
126
127
128 def remote_api(req_json, osdf_config, service_type="placement"):
129     """Make a request to policy and return response -- it accounts for multiple requests that be needed
130     :param req_json: policy request object (can have multiple policy names)
131     :param osdf_config: main config that will have credential information
132     :param service_type: the type of service to call: "placement", "scheduling"
133     :return: all related policies and provStatus retrieved from Subscriber policy
134     """
135     prov_status = None
136     config = osdf_config.deployment
137     uid, passwd = config['policyPlatformUsername'], config['policyPlatformPassword']
138     pcuid, pcpasswd = config['policyClientUsername'], config['policyClientPassword']
139     headers = {"ClientAuth": base64.b64encode(bytes("{}:{}".format(pcuid, pcpasswd), "ascii"))}
140     headers.update({'Environment': config['policyPlatformEnv']})
141     url = config['policyPlatformUrl']
142     rc = RestClient(userid=uid, passwd=passwd, headers=headers, url=url, log_func=debug_log.debug)
143
144     if osdf_config.core['policy_info'][service_type]['policy_fetch'] == "by_name":
145         policies = get_by_name(rc, req_json[service_type + "Info"]['policyId'], wildcards=True)
146     elif osdf_config.core['policy_info'][service_type]['policy_fetch'] == "by_name_no_wildcards":
147         policies = get_by_name(rc, req_json[service_type + "Info"]['policyId'], wildcards=False)
148     else:  # Get policy by scope
149         policies, prov_status = get_by_scope(rc, req_json, osdf_config.core, service_type)
150
151     # policies in res are list of lists, so flatten them; also only keep config part
152     formatted_policies = []
153     for x in itertools.chain(*policies):
154         if x['config'] is None:
155             raise BusinessException("Config not found for policy with name %s" % x['policyName'])
156         else:
157             formatted_policies.append(json.loads(x['config']))
158     return formatted_policies, prov_status
159
160
161 def local_policies_location(req_json, osdf_config, service_type):
162     """
163     Get folder and list of policy_files if "local policies" option is enabled
164     :param service_type: placement supported for now, but can be any other service
165     :return: a tuple (folder, file_list) or None
166     """
167     lp = osdf_config.core.get('osdf_temp', {}).get('local_policies', {})
168     if lp.get('global_disabled'):
169         return None  # short-circuit to disable all local policies
170     if lp.get('local_{}_policies_enabled'.format(service_type)):
171         if service_type == "scheduling":
172             return lp.get('{}_policy_dir'.format(service_type)), lp.get('{}_policy_files'.format(service_type))
173         else:
174             required_node = osdf_config.core['policy_info'][service_type]['policy_scope']['service_name']
175             model_name = retrieve_node(req_json, required_node)
176             service_name = model_name  # TODO: data_mapping.get_service_type(model_name)
177             return lp.get('{}_policy_dir_{}'.format(service_type, service_name.lower())), \
178                    lp.get('{}_policy_files_{}'.format(service_type, service_name.lower()))
179     return None
180
181
182 def get_policies(request_json, service_type):
183     """Validate the request and get relevant policies
184     :param request_json: Request object
185     :param service_type: the type of service to call: "placement", "scheduling"
186     :return: policies associated with this request and provStatus retrieved from Subscriber policy
187     """
188     prov_status = []
189     req_info = request_json['requestInfo']
190     req_id = req_info['requestId']
191     metrics_log.info(MH.requesting("policy", req_id))
192     local_info = local_policies_location(request_json, osdf_config, service_type)
193
194     if local_info:  # tuple containing location and list of files
195         to_filter = None
196         if osdf_config.core['policy_info'][service_type]['policy_fetch'] == "by_name":
197             to_filter = request_json[service_type + "Info"]['policyId']
198         policies = get_local_policies(local_info[0], local_info[1], to_filter)
199     else:
200         policies, prov_status = remote_api(request_json, osdf_config, service_type)
201         
202     return policies, prov_status