2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2021 Nordix Foundation.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.pdp.xacml.application.common.std;
26 import com.att.research.xacml.api.Advice;
27 import com.att.research.xacml.api.Identifier;
28 import com.att.research.xacml.api.Obligation;
29 import com.att.research.xacml.api.Request;
30 import com.att.research.xacml.api.XACML3;
31 import com.att.research.xacml.std.IdentifierImpl;
32 import com.att.research.xacml.util.XACMLPolicyWriter;
33 import java.io.ByteArrayOutputStream;
34 import java.io.IOException;
35 import java.nio.charset.StandardCharsets;
36 import java.nio.file.Files;
37 import java.nio.file.Path;
38 import java.nio.file.Paths;
39 import java.util.Collection;
40 import java.util.HashMap;
41 import java.util.LinkedHashMap;
42 import java.util.LinkedList;
43 import java.util.List;
45 import java.util.Map.Entry;
46 import lombok.NoArgsConstructor;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
54 import org.apache.commons.lang3.tuple.Pair;
55 import org.onap.policy.common.endpoints.http.client.HttpClient;
56 import org.onap.policy.common.utils.coder.CoderException;
57 import org.onap.policy.common.utils.coder.StandardCoder;
58 import org.onap.policy.common.utils.coder.StandardYamlCoder;
59 import org.onap.policy.models.decisions.concepts.DecisionRequest;
60 import org.onap.policy.models.decisions.concepts.DecisionResponse;
61 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
62 import org.onap.policy.models.tosca.authorative.concepts.ToscaDataType;
63 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
64 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
65 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
66 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
67 import org.onap.policy.pdp.xacml.application.common.OnapObligation;
68 import org.onap.policy.pdp.xacml.application.common.PolicyApiCaller;
69 import org.onap.policy.pdp.xacml.application.common.PolicyApiException;
70 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
71 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
72 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslatorUtils;
73 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
74 import org.onap.policy.pdp.xacml.application.common.matchable.MatchableCallback;
75 import org.onap.policy.pdp.xacml.application.common.matchable.MatchablePolicyType;
76 import org.onap.policy.pdp.xacml.application.common.matchable.MatchableProperty;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
81 * This standard matchable translator uses Policy Types that contain "matchable" field in order
82 * to translate policies.
84 * @author pameladragosh
88 public class StdMatchableTranslator extends StdBaseTranslator implements MatchableCallback {
90 private static final Logger LOGGER = LoggerFactory.getLogger(StdMatchableTranslator.class);
91 private static final StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
93 private final Map<ToscaConceptIdentifier, ToscaServiceTemplate> matchablePolicyTypes = new HashMap<>();
94 private final Map<ToscaConceptIdentifier, MatchablePolicyType> matchableCache = new HashMap<>();
97 private HttpClient apiClient;
99 private Path pathForData;
102 public Request convertRequest(DecisionRequest request) throws ToscaPolicyConversionException {
103 LOGGER.info("Converting Request {}", request);
105 return StdMatchablePolicyRequest.createInstance(request);
106 } catch (XacmlApplicationException e) {
107 throw new ToscaPolicyConversionException("Failed to convert DecisionRequest", e);
112 * scanObligations - scans the list of obligations and make appropriate method calls to process
115 * @param obligations Collection of obligation objects
116 * @param decisionResponse DecisionResponse object used to store any results from obligations.
119 protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
121 // Implementing a crude "closest match" on the results, which means we will strip out
122 // any policies that has the lower weight than any of the others.
124 // Most likely these are "default" policies with a weight of zero, but not always.
126 // It is possible to have multiple policies with an equal weight, that is desired.
128 // So we need to track each policy type separately and the weights for each policy.
130 // policy-type -> weight -> List({policy-id, policy-content}, {policy-id, policy-content})
132 Map<String, Map<Integer, List<Pair<String, Map<String, Object>>>>> closestMatches = new LinkedHashMap<>();
134 // Now scan the list of obligations
136 for (Obligation obligation : obligations) {
137 Identifier obligationId = obligation.getId();
138 LOGGER.info("Obligation: {}", obligationId);
139 if (ToscaDictionary.ID_OBLIGATION_REST_BODY.equals(obligationId)) {
140 scanClosestMatchObligation(closestMatches, obligation);
142 LOGGER.warn("Unsupported Obligation Id {}", obligation.getId());
146 // Now add all the policies to the DecisionResponse
148 closestMatches.forEach((thePolicyType, weightMap) ->
149 weightMap.forEach((weight, policies) ->
150 policies.forEach(policy -> {
151 LOGGER.info("Policy {}", policy);
152 decisionResponse.getPolicies().put(policy.getLeft(), policy.getRight());
159 protected void scanAdvice(Collection<Advice> advice, DecisionResponse decisionResponse) {
160 LOGGER.warn("scanAdvice not supported by {}", this.getClass());
164 * scanClosestMatchObligation - scans for the obligation specifically holding policy
165 * contents and their details.
167 * @param closestMatches Map holding the current set of highest weight policy types
168 * @param obligation Obligation object
170 protected void scanClosestMatchObligation(
171 Map<String, Map<Integer, List<Pair<String, Map<String, Object>>>>> closestMatches, Obligation obligation) {
173 // Create our OnapObligation object
175 var onapObligation = new OnapObligation(obligation);
177 // All 4 *should* be there
179 if (onapObligation.getPolicyId() == null || onapObligation.getPolicyContent() == null
180 || onapObligation.getPolicyType() == null || onapObligation.getWeight() == null) {
181 LOGGER.error("Missing an expected attribute in obligation.");
187 String policyId = onapObligation.getPolicyId();
188 String policyType = onapObligation.getPolicyType();
189 Map<String, Object> policyContent = onapObligation.getPolicyContentAsMap();
190 int policyWeight = onapObligation.getWeight();
192 // If the Policy Type exists, get the weight map.
194 Map<Integer, List<Pair<String, Map<String, Object>>>> weightMap = closestMatches.get(policyType);
195 if (weightMap != null) {
197 // Only need to check first one - as we will ensure there is only one weight
199 Entry<Integer, List<Pair<String, Map<String, Object>>>> firstEntry =
200 weightMap.entrySet().iterator().next();
201 if (policyWeight < firstEntry.getKey()) {
203 // Existing policies have a greater weight, so we will not add it
205 LOGGER.info("{} is lesser weight {} than current policies, will not return it", policyWeight,
206 firstEntry.getKey());
207 } else if (firstEntry.getKey().equals(policyWeight)) {
209 // Same weight - we will add it
211 LOGGER.info("Same weight {}, adding policy", policyWeight);
212 firstEntry.getValue().add(Pair.of(policyId, policyContent));
215 // The weight is greater, so we need to remove the other policies
216 // and point to this one.
218 LOGGER.info("New policy has greater weight {}, replacing {}", policyWeight, firstEntry.getKey());
219 List<Pair<String, Map<String, Object>>> listPolicies = new LinkedList<>();
220 listPolicies.add(Pair.of(policyId, policyContent));
222 weightMap.put(policyWeight, listPolicies);
226 // Create a new entry
228 LOGGER.info("New entry {} weight {}", policyType, policyWeight);
229 List<Pair<String, Map<String, Object>>> listPolicies = new LinkedList<>();
230 listPolicies.add(Pair.of(policyId, policyContent));
231 Map<Integer, List<Pair<String, Map<String, Object>>>> newWeightMap = new LinkedHashMap<>();
232 newWeightMap.put(policyWeight, listPolicies);
233 closestMatches.put(policyType, newWeightMap);
238 public Object convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
240 // Get the TOSCA Policy Type for this policy
242 ToscaServiceTemplate toscaPolicyTypeTemplate = this.findPolicyType(toscaPolicy.getTypeIdentifier());
244 // If we don't have any TOSCA policy types, then we cannot know
245 // which properties are matchable.
247 if (toscaPolicyTypeTemplate == null) {
248 throw new ToscaPolicyConversionException(
249 "Cannot retrieve Policy Type definition for policy " + toscaPolicy.getName());
252 // Policy name should be at the root
254 String policyName = toscaPolicy.getMetadata().get(POLICY_ID);
256 // Set it as the policy ID
258 var newPolicyType = new PolicyType();
259 newPolicyType.setPolicyId(policyName);
261 // Optional description
263 newPolicyType.setDescription(toscaPolicy.getDescription());
265 // There should be a metadata section
267 fillMetadataSection(newPolicyType, toscaPolicy.getMetadata());
269 // Set the combining rule
271 newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_FIRST_APPLICABLE.stringValue());
273 // Generate the TargetType - the policy should not be evaluated
274 // unless all the matchable properties it cares about are matched.
276 Pair<TargetType, Integer> pairGenerated = generateTargetType(toscaPolicy, toscaPolicyTypeTemplate);
277 newPolicyType.setTarget(pairGenerated.getLeft());
279 // Now represent the policy as Json
281 var coder = new StandardCoder();
284 jsonPolicy = coder.encode(toscaPolicy);
285 } catch (CoderException e) {
286 throw new ToscaPolicyConversionException("Failed to encode policy to json", e);
289 // Add it as an obligation
291 addObligation(newPolicyType, policyName, jsonPolicy, pairGenerated.getRight(), toscaPolicy.getType());
293 // Now create the Permit Rule.
295 var rule = new RuleType();
296 rule.setDescription("Default is to PERMIT if the policy matches.");
297 rule.setRuleId(policyName + ":rule");
298 rule.setEffect(EffectType.PERMIT);
299 rule.setTarget(new TargetType());
301 // The rule contains the Condition which adds logic for
302 // optional policy-type filtering.
304 rule.setCondition(generateConditionForPolicyType(toscaPolicy.getType()));
306 // Add the rule to the policy
308 newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
310 // Log output of the policy
312 try (var os = new ByteArrayOutputStream()) {
313 XACMLPolicyWriter.writePolicyFile(os, newPolicyType);
314 LOGGER.info("{}", os);
315 } catch (IOException e) {
316 LOGGER.error("Failed to create byte array stream", e);
321 return newPolicyType;
325 public ToscaPolicyType retrievePolicyType(String derivedFrom) {
326 ToscaServiceTemplate template = this.findPolicyType(new ToscaConceptIdentifier(derivedFrom, "1.0.0"));
327 if (template == null) {
328 LOGGER.error("Could not retrieve Policy Type {}", derivedFrom);
331 return template.getPolicyTypes().get(derivedFrom);
335 public ToscaDataType retrieveDataType(String datatype) {
337 // Our outer class is not storing the current template being scanned
339 LOGGER.error("this retrieveDataType should not be called.");
343 private class MyMatchableCallback implements MatchableCallback {
344 private StdMatchableTranslator translator;
345 private ToscaServiceTemplate template;
347 public MyMatchableCallback(StdMatchableTranslator translator, ToscaServiceTemplate template) {
348 this.translator = translator;
349 this.template = template;
353 public ToscaPolicyType retrievePolicyType(String derivedFrom) {
354 ToscaPolicyType policyType = this.template.getPolicyTypes().get(derivedFrom);
355 if (policyType != null) {
358 return translator.retrievePolicyType(derivedFrom);
362 public ToscaDataType retrieveDataType(String datatype) {
363 return this.template.getDataTypes().get(datatype);
369 * For generating target type, we scan for matchable properties
370 * and use those to build the policy.
372 * @param policy the policy
373 * @param template template containing the policy
374 * @return {@code Pair<TargetType, Integer>} Returns a TargetType and a Total Weight of matchables.
376 protected Pair<TargetType, Integer> generateTargetType(ToscaPolicy policy, ToscaServiceTemplate template) {
380 var target = new TargetType();
382 // See if we have a matchable in the cache already
384 var matchablePolicyType = matchableCache.get(policy.getTypeIdentifier());
386 // If not found, create one
388 if (matchablePolicyType == null) {
392 var myCallback = new MyMatchableCallback(this, template);
394 // Create the matchable
396 matchablePolicyType = new MatchablePolicyType(
397 template.getPolicyTypes().get(policy.getType()), myCallback);
401 matchableCache.put(policy.getTypeIdentifier(), matchablePolicyType);
404 // Fill in the target type with potential matchables
407 fillTargetTypeWithMatchables(target, matchablePolicyType, policy.getProperties());
408 } catch (ToscaPolicyConversionException e) {
409 LOGGER.error("Could not generate target type", e);
412 // There may be a case for default policies there is no weight - need to clean
413 // up the target then else PDP will report bad policy missing AnyOf
415 int weight = calculateWeight(target);
416 LOGGER.debug("Weight is {} for policy {}", weight, policy.getName());
418 // Assume the number of AllOf's is the weight for now
420 return Pair.of(target, weight);
423 @SuppressWarnings("unchecked")
424 protected void fillTargetTypeWithMatchables(TargetType target, MatchablePolicyType matchablePolicyType,
425 Map<String, Object> properties) throws ToscaPolicyConversionException {
426 for (Entry<String, Object> entrySet : properties.entrySet()) {
427 String propertyName = entrySet.getKey();
428 Object propertyValue = entrySet.getValue();
429 MatchableProperty matchable = matchablePolicyType.get(propertyName);
430 if (matchable != null) {
432 // Construct attribute id
434 Identifier id = new IdentifierImpl(ToscaDictionary.ID_RESOURCE_MATCHABLE + propertyName);
436 // Depending on what type it is, add it into the target
438 ToscaPolicyTranslatorUtils.buildAndAppendTarget(target,
439 matchable.getType().generate(propertyValue, id));
444 // Here is the special case where we look for a Collection of values that may
445 // contain potential matchables
447 if (propertyValue instanceof List) {
448 for (Object listValue : ((List<?>) propertyValue)) {
449 if (listValue instanceof Map) {
450 fillTargetTypeWithMatchables(target, matchablePolicyType, (Map<String, Object>) listValue);
453 } else if (propertyValue instanceof Map) {
454 fillTargetTypeWithMatchables(target, matchablePolicyType, (Map<String, Object>) propertyValue);
459 protected int calculateWeight(TargetType target) {
461 for (AnyOfType anyOf : target.getAnyOf()) {
462 for (AllOfType allOf : anyOf.getAllOf()) {
463 weight += allOf.getMatch().size();
471 * findPolicyType - given the ToscaConceptIdentifier, finds it in memory, or
472 * then tries to find it either locally on disk or pull it from the Policy
473 * Lifecycle API the given TOSCA Policy Type.
475 * @param policyTypeId ToscaConceptIdentifier to find
476 * @return ToscaPolicyType object. Can be null if failure.
478 protected ToscaServiceTemplate findPolicyType(ToscaConceptIdentifier policyTypeId) {
480 // Is it loaded in memory?
482 ToscaServiceTemplate policyTemplate = this.matchablePolicyTypes.get(policyTypeId);
483 if (policyTemplate == null) {
487 policyTemplate = this.loadPolicyType(policyTypeId);
491 if (policyTemplate != null) {
492 this.matchablePolicyTypes.put(policyTypeId, policyTemplate);
498 return policyTemplate;
502 * loadPolicyType - Tries to load the given ToscaConceptIdentifier from local
503 * storage. If it does not exist, will then attempt to pull from Policy Lifecycle
506 * @param policyTypeId ToscaConceptIdentifier input
507 * @return ToscaPolicyType object. Null if failure.
509 protected ToscaServiceTemplate loadPolicyType(ToscaConceptIdentifier policyTypeId) {
511 // Construct what the file name should be
513 var policyTypePath = this.constructLocalFilePath(policyTypeId);
520 // If it exists locally, read the bytes in
522 bytes = Files.readAllBytes(policyTypePath);
523 } catch (IOException e) {
525 // Does not exist locally, so let's GET it from the policy api
527 LOGGER.error("PolicyType not found in data area yet {}", policyTypePath, e);
529 // So let's pull it from API REST call and save it locally
531 return this.pullPolicyType(policyTypeId, policyTypePath);
534 // Success - we have read locally the policy type. Now bring it into our
537 LOGGER.info("Read in local policy type {}", policyTypePath.toAbsolutePath());
540 // Decode the template
542 ToscaServiceTemplate template = standardYamlCoder.decode(new String(bytes, StandardCharsets.UTF_8),
543 ToscaServiceTemplate.class);
545 // Ensure all the fields are setup correctly
547 var jtst = new JpaToscaServiceTemplate();
548 jtst.fromAuthorative(template);
549 return jtst.toAuthorative();
550 } catch (CoderException e) {
551 LOGGER.error("Failed to decode tosca template for {}", policyTypePath, e);
554 // Hopefully we never get here
556 LOGGER.error("Failed to find/load policy type {}", policyTypeId);
561 * pullPolicyType - pulls the given ToscaConceptIdentifier from the Policy Lifecycle API.
562 * If successful, will store it locally given the policyTypePath.
564 * @param policyTypeId ToscaConceptIdentifier
565 * @param policyTypePath Path object to store locally
566 * @return ToscaPolicyType object. Null if failure.
568 protected synchronized ToscaServiceTemplate pullPolicyType(ToscaConceptIdentifier policyTypeId,
569 Path policyTypePath) {
571 // This is what we return
573 ToscaServiceTemplate policyTemplate = null;
575 var api = new PolicyApiCaller(this.apiClient);
577 policyTemplate = api.getPolicyType(policyTypeId);
578 } catch (PolicyApiException e) {
579 LOGGER.error("Failed to make API call", e);
582 LOGGER.info("Successfully pulled {}", policyTypeId);
587 standardYamlCoder.encode(policyTypePath.toFile(), policyTemplate);
588 } catch (CoderException e) {
589 LOGGER.error("Failed to store {} locally to {}", policyTypeId, policyTypePath, e);
592 // Done return the policy type
594 return policyTemplate;
598 * constructLocalFilePath - common method to ensure the name of the local file for the
599 * policy type is the same.
601 * @param policyTypeId ToscaConceptIdentifier
602 * @return Path object
604 protected Path constructLocalFilePath(ToscaConceptIdentifier policyTypeId) {
605 return Paths.get(this.pathForData.toAbsolutePath().toString(), policyTypeId.getName() + "-"
606 + policyTypeId.getVersion() + ".yaml");