Merge "Push policy adapter code (adapted from ECOMP)"
[optf/osdf.git] / 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 = data_mapping.get_request_service_type(req)
113     if service_name is None:
114         service_name = data_mapping.get_service_type(model_name)
115     scope = pscope['scope_{}'.format(service_name.lower())]
116     subscriber_role, prov_status = get_subscriber_role(rest_client, req, pmain, service_name, scope)
117     policy_type_list = pmain['policy_type_{}'.format(service_name.lower())]
118     for policy_type in policy_type_list:
119         policy_scope = {"policyName": "{}.*".format(scope),
120                         "configAttributes": {
121                             "serviceType": "{}".format(service_name),
122                             "service": "{}".format(policy_type),
123                             "subscriberRole": "{}".format(subscriber_role)}
124                         }
125         policy_list.append(rest_client.request(json=policy_scope))
126     return policy_list, prov_status
127
128
129 def remote_api(req_json, osdf_config, service_type="placement"):
130     """Make a request to policy and return response -- it accounts for multiple requests that be needed
131     :param req_json: policy request object (can have multiple policy names)
132     :param osdf_config: main config that will have credential information
133     :param service_type: the type of service to call: "placement", "scheduling"
134     :return: all related policies and provStatus retrieved from Subscriber policy
135     """
136 #     if not req_json[service_type + "Info"]['policyId']:
137 #         return []
138
139     config = osdf_config.deployment
140     uid, passwd = config['policyPlatformUsername'], config['policyPlatformPassword']
141     pcuid, pcpasswd = config['policyClientUsername'], config['policyClientPassword']
142     headers = {"ClientAuth": base64.b64encode(bytes("{}:{}".format(pcuid, pcpasswd), "ascii"))}
143     headers.update({'Environment': config['policyPlatformEnv']})
144     url = config['policyPlatformUrl']
145     rc = RestClient(userid=uid, passwd=passwd, headers=headers, url=url, log_func=debug_log.debug)
146
147     if osdf_config.core['policy_info'][service_type]['policy_fetch'] == "by_name":
148         policies = get_by_name(rc, req_json[service_type + "Info"]['policyId'], wildcards=True)
149     elif osdf_config.core['policy_info'][service_type]['policy_fetch'] == "by_name_no_wildcards":
150         policies = get_by_name(rc, req_json[service_type + "Info"]['policyId'], wildcards=False)
151     else:  # Get policy by scope
152         policies, prov_status = get_by_scope(rc, req_json, osdf_config.core, service_type)
153
154     # policies in res are list of lists, so flatten them; also only keep config part
155     formatted_policies = []
156     for x in itertools.chain(*policies):
157         if x['config'] is None:
158             raise BusinessException("Config not found for policy with name %s" % x['policyName'])
159         else:
160             formatted_policies.append(json.loads(x['config']))
161     return formatted_policies, prov_status
162
163
164 def local_policies_location(req_json, osdf_config, service_type):
165     """
166     Get folder and list of policy_files if "local policies" option is enabled
167     :param service_type: placement supported for now, but can be any other service
168     :return: a tuple (folder, file_list) or None
169     """
170     lp = osdf_config.core.get('osdf_hacks', {}).get('local_policies', {})
171     if lp.get('global_disabled'):
172         return None  # short-circuit to disable all local policies
173     if lp.get('local_{}_policies_enabled'.format(service_type)):
174         if service_type == "scheduling":
175             return lp.get('{}_policy_dir'.format(service_type)), lp.get('{}_policy_files'.format(service_type))
176         else:
177             model_name = retrieve_node(req_json, osdf_config.core['policy_info'][service_type]['policy_scope']['service_name'])
178             service_name = data_mapping.get_service_type(model_name)
179             return lp.get('{}_policy_dir_{}'.format(service_type, service_name.lower())), lp.get('{}_policy_files_{}'.format(service_type, service_name.lower()))
180     return None
181
182
183 def get_policies(request_json, service_type):
184     """Validate the request and get relevant policies
185     :param request_json: Request object
186     :param service_type: the type of service to call: "placement", "scheduling"
187     :return: policies associated with this request and provStatus retrieved from Subscriber policy
188     """
189     prov_status = []
190     req_info = request_json['requestInfo']
191     req_id = req_info['requestId']
192     metrics_log.info(MH.requesting("policy", req_id))
193     local_info = local_policies_location(request_json, osdf_config, service_type)
194
195     if local_info:  # tuple containing location and list of files
196         to_filter = None
197         if osdf_config.core['policy_info'][service_type]['policy_fetch'] == "by_name":
198             to_filter = request_json[service_type + "Info"]['policyId']
199         policies = get_local_policies(local_info[0], local_info[1], to_filter)
200     else:
201         policies, prov_status= remote_api(request_json, osdf_config, service_type)
202         
203     return policies, prov_status