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 # -------------------------------------------------------------------------
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 policy_name_as_regex, retrieve_node
28 from osdf.utils.programming_utils import list_flatten, dot_notation
29 from osdf.config.base import osdf_config
30 from osdf.logging.osdf_logging import audit_log, MH, metrics_log, debug_log
31 from osdf.utils.interfaces import RestClient
34 def get_by_name(rest_client, policy_name_list, wildcards=True):
36 for policy_name in policy_name_list:
38 query_name = policy_name
40 query_name = policy_name_as_regex(query_name)
41 policy_list.append(rest_client.request(json={"policyName": query_name}))
42 except RequestException as err:
43 audit_log.warn("Error in fetching policy: " + policy_name)
44 raise BusinessException("Cannot fetch policy {}: ".format(policy_name), err)
48 def get_by_scope(rest_client, req, config_local, type_service):
49 """ Get policies by scopes as defined in the configuration file.
50 :param rest_client: a rest client object to make a call.
51 :param req: an optimization request.
52 :param config_local: application configuration file.
53 :param type_service: the type of optimization service.
54 :return: policies in the form of list of list where inner list contains policies for a single a scope.
57 references = config_local.get('references', {})
58 pscope = config_local.get('policy_info', {}).get(type_service, {}).get('policy_scope', {})
59 service_name = dot_notation(req, references.get('service_name', {}).get('value', None))
60 primary_scope = pscope['{}_scope'.format(service_name.lower() if service_name else "default")]
61 for sec_scope in pscope.get('secondary_scopes', []):
62 policies, scope_fields = [], []
63 for field in sec_scope:
64 scope_fields.extend([get_scope_fields(field, references, req, list_flatten(scope_policies))
65 if 'get_param' in field else field])
66 scope_fields = set(list_flatten(scope_fields))
67 for scope in scope_fields:
68 policies.extend(policy_api_call(rest_client, primary_scope, scope))
69 scope_policies.append([policy for policy in policies
70 if scope_fields <= set(json.loads(policy['config'])['content']['policyScope'])])
74 def get_scope_fields(field, references, req, policy_info):
75 """ Retrieve the values for scope fields from a request and policies as per the configuration
76 and references defined in a configuration file. If the value of a scope field missing in a request or
77 policies, throw an exception since correct policies cannot be retrieved.
78 :param field: details on a scope field from a configuration file.
79 :param references: references defined in a configuration file.
80 :param req: an optimization request.
81 :param policy_info: a list of policies.
82 :return: scope fields retrieved from a request and policies.
84 ref_source = references.get(field.get('get_param', ""), {}).get('source')
85 ref_value = references.get(field.get('get_param', ""), {}).get('value')
86 if ref_source == "request":
87 scope_field = dot_notation(req, ref_value)
90 raise BusinessException("Field {} is missing a value in a request".format(ref_value.split('.')[-1]))
93 for policy in policy_info:
94 policy_content = json.loads(policy.get('config', "{}"))
95 if policy_content.get('content', {}).get('policyType', "invalid_policy") == ref_source:
96 scope_fields.append(dot_notation(policy_content, ref_value))
97 scope_values = list_flatten(scope_fields)
98 if len(scope_values) > 0:
100 raise BusinessException("Field {} is missing a value in all policies of type {}".format(
101 ref_value.split('.')[-1], ref_source))
104 def policy_api_call(rest_client, primary_scope, scope_field):
105 """ Makes a getConfig API call to the policy system to retrieve policies matching a scope.
106 :param rest_client: rest client object to make a call
107 :param primary_scope: the primary scope of policies, which is a folder in the policy system
108 where policies are stored.
109 :param scope_field: the secondary scope of policies, which is a collection of domain values.
110 :return: a list of policies matching both primary and secondary scopes.
112 api_call_body = {"policyName": "{}.*".format(primary_scope),
113 "configAttributes": {"policyScope": "{}".format(scope_field)}}
114 return rest_client.request(json=api_call_body)
117 def remote_api(req_json, osdf_config, service_type="placement"):
118 """Make a request to policy and return response -- it accounts for multiple requests that be needed
119 :param req_json: policy request object (can have multiple policy names)
120 :param osdf_config: main config that will have credential information
121 :param service_type: the type of service to call: "placement", "scheduling"
122 :return: all related policies and provStatus retrieved from Subscriber policy
124 config = osdf_config.deployment
125 uid, passwd = config['policyPlatformUsername'], config['policyPlatformPassword']
126 pcuid, pcpasswd = config['policyClientUsername'], config['policyClientPassword']
127 headers = {"ClientAuth": base64.b64encode(bytes("{}:{}".format(pcuid, pcpasswd), "ascii"))}
128 headers.update({'Environment': config['policyPlatformEnv']})
129 url = config['policyPlatformUrl']
130 rc = RestClient(userid=uid, passwd=passwd, headers=headers, url=url, log_func=debug_log.debug)
132 if osdf_config.core['policy_info'][service_type]['policy_fetch'] == "by_name":
133 policies = get_by_name(rc, req_json[service_type + "Info"]['policyId'], wildcards=True)
134 elif osdf_config.core['policy_info'][service_type]['policy_fetch'] == "by_name_no_wildcards":
135 policies = get_by_name(rc, req_json[service_type + "Info"]['policyId'], wildcards=False)
137 policies = get_by_scope(rc, req_json, osdf_config.core, service_type)
139 formatted_policies = []
140 for x in itertools.chain(*policies):
141 if x['config'] is None:
142 raise BusinessException("Config not found for policy with name %s" % x['policyName'])
144 formatted_policies.append(json.loads(x['config']))
145 return formatted_policies
148 def local_policies_location(req_json, osdf_config, service_type):
150 Get folder and list of policy_files if "local policies" option is enabled
151 :param service_type: placement supported for now, but can be any other service
152 :return: a tuple (folder, file_list) or None
154 lp = osdf_config.core.get('osdf_temp', {}).get('local_policies', {})
155 if lp.get('global_disabled'):
156 return None # short-circuit to disable all local policies
157 if lp.get('local_{}_policies_enabled'.format(service_type)):
158 if service_type == "scheduling":
159 return lp.get('{}_policy_dir'.format(service_type)), lp.get('{}_policy_files'.format(service_type))
161 service_name = req_json['serviceInfo']['serviceName'] # TODO: data_mapping.get_service_type(model_name)
162 return lp.get('{}_policy_dir_{}'.format(service_type, service_name.lower())), \
163 lp.get('{}_policy_files_{}'.format(service_type, service_name.lower()))
167 def get_policies(request_json, service_type):
168 """Validate the request and get relevant policies
169 :param request_json: Request object
170 :param service_type: the type of service to call: "placement", "scheduling"
171 :return: policies associated with this request and provStatus retrieved from Subscriber policy
173 req_info = request_json['requestInfo']
174 req_id = req_info['requestId']
175 metrics_log.info(MH.requesting("policy", req_id))
176 local_info = local_policies_location(request_json, osdf_config, service_type)
178 if local_info: # tuple containing location and list of files
180 if osdf_config.core['policy_info'][service_type]['policy_fetch'] == "by_name":
181 to_filter = request_json[service_type + "Info"]['policyId']
182 policies = get_local_policies(local_info[0], local_info[1], to_filter)
184 policies = remote_api(request_json, osdf_config, service_type)