2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.pdp.xacml.application.common.std;
25 import com.att.research.xacml.api.Identifier;
26 import com.att.research.xacml.api.Request;
27 import com.att.research.xacml.api.XACML3;
28 import com.att.research.xacml.std.IdentifierImpl;
29 import com.att.research.xacml.util.XACMLPolicyWriter;
30 import java.io.ByteArrayOutputStream;
31 import java.io.IOException;
32 import java.nio.charset.StandardCharsets;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.nio.file.Paths;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.HashMap;
41 import java.util.List;
43 import java.util.Map.Entry;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
51 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
52 import org.onap.policy.common.utils.coder.CoderException;
53 import org.onap.policy.common.utils.coder.StandardCoder;
54 import org.onap.policy.common.utils.coder.StandardYamlCoder;
55 import org.onap.policy.models.decisions.concepts.DecisionRequest;
56 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
57 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
58 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
59 import org.onap.policy.models.tosca.authorative.concepts.ToscaProperty;
60 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
61 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
62 import org.onap.policy.pdp.xacml.application.common.PolicyApiCaller;
63 import org.onap.policy.pdp.xacml.application.common.PolicyApiException;
64 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
65 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
66 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslatorUtils;
67 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
72 * This standard matchable translator uses Policy Types that contain "matchable" field in order
73 * to translate policies.
75 * @author pameladragosh
78 public class StdMatchableTranslator extends StdBaseTranslator {
80 private static final Logger LOGGER = LoggerFactory.getLogger(StdMatchableTranslator.class);
81 private static final StandardYamlCoder standardYamlCoder = new StandardYamlCoder();
83 private final Map<ToscaPolicyTypeIdentifier, ToscaPolicyType> matchablePolicyTypes = new HashMap<>();
85 private RestServerParameters apiRestParameters;
87 private Path pathForData;
89 public StdMatchableTranslator() {
94 public Request convertRequest(DecisionRequest request) {
95 LOGGER.info("Converting Request {}", request);
97 return StdMatchablePolicyRequest.createInstance(request);
98 } catch (XacmlApplicationException e) {
99 LOGGER.error("Failed to convert DecisionRequest: {}", e);
102 // TODO throw exception
108 public PolicyType convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
110 // Get the TOSCA Policy Type for this policy
112 Collection<ToscaPolicyType> toscaPolicyTypes = this.getPolicyTypes(toscaPolicy.getTypeIdentifier());
114 // If we don't have any TOSCA policy types, then we cannot know
115 // which properties are matchable.
117 if (toscaPolicyTypes.isEmpty()) {
118 throw new ToscaPolicyConversionException(
119 "Cannot retrieve Policy Type definition for policy " + toscaPolicy.getName());
122 // Policy name should be at the root
124 String policyName = toscaPolicy.getMetadata().get(POLICY_ID);
126 // Set it as the policy ID
128 PolicyType newPolicyType = new PolicyType();
129 newPolicyType.setPolicyId(policyName);
131 // Optional description
133 newPolicyType.setDescription(toscaPolicy.getDescription());
135 // There should be a metadata section
137 fillMetadataSection(newPolicyType, toscaPolicy.getMetadata());
139 // Set the combining rule
141 newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_FIRST_APPLICABLE.stringValue());
143 // Generate the TargetType
145 newPolicyType.setTarget(new TargetType());
147 // Now represent the policy as Json
149 StandardCoder coder = new StandardCoder();
152 jsonPolicy = coder.encode(toscaPolicy);
153 } catch (CoderException e) {
154 throw new ToscaPolicyConversionException("Failed to encode policy to json", e);
157 // Add it as an obligation
159 addObligation(newPolicyType, jsonPolicy);
161 // Now create the Permit Rule for all the
162 // matchable properties.
164 RuleType rule = new RuleType();
165 rule.setDescription("Default is to PERMIT if the policy matches.");
166 rule.setRuleId(policyName + ":rule");
167 rule.setEffect(EffectType.PERMIT);
168 rule.setTarget(generateTargetType(toscaPolicy.getProperties(), toscaPolicyTypes));
169 rule.setCondition(generateConditionForPolicyType(toscaPolicy.getType()));
171 // Add the rule to the policy
173 newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
175 // If a Decision is for a specific policy-type, make sure
176 // there is a rule for it.
178 rule = new RuleType();
179 rule.setDescription("Match on policy-type " + toscaPolicy.getType());
180 rule.setRuleId(policyName + ":rule:policy-type");
181 rule.setEffect(EffectType.PERMIT);
182 TargetType target = new TargetType();
183 target.getAnyOf().add(this.generateAnyOfForPolicyType(toscaPolicy.getType()));
184 rule.setTarget(target);
186 // Add the rule to the policy
188 newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
190 // Log output of the policy
192 try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
193 XACMLPolicyWriter.writePolicyFile(os, newPolicyType);
194 LOGGER.info("{}", os);
195 } catch (IOException e) {
196 LOGGER.error("Failed to create byte array stream", e);
201 return newPolicyType;
205 * For generating target type, we scan for matchable properties
206 * and use those to build the policy.
208 * @param properties Properties section of policy
209 * @param policyTypes Collection of policy Type to find matchable metadata
210 * @return TargetType object
212 protected TargetType generateTargetType(Map<String, Object> properties, Collection<ToscaPolicyType> policyTypes) {
213 TargetType targetType = new TargetType();
215 // Iterate the properties
217 for (Entry<String, Object> entrySet : properties.entrySet()) {
219 // Find matchable properties
221 if (isMatchable(entrySet.getKey(), policyTypes)) {
222 LOGGER.info("Found matchable property {}", entrySet.getValue());
223 generateMatchable(targetType, entrySet.getKey(), entrySet.getValue());
231 * isMatchable - Iterates through available TOSCA Policy Types to determine if a property
232 * should be treated as matchable.
234 * @param propertyName Name of property
235 * @param policyTypes Collection of TOSCA Policy Types to scan
236 * @return true if matchable
238 protected boolean isMatchable(String propertyName, Collection<ToscaPolicyType> policyTypes) {
239 for (ToscaPolicyType policyType : policyTypes) {
240 for (Entry<String, ToscaProperty> propertiesEntry : policyType.getProperties().entrySet()) {
241 if (! propertiesEntry.getKey().equals(propertyName)
242 || propertiesEntry.getValue().getMetadata() == null) {
245 for (Entry<String, String> entrySet : propertiesEntry.getValue().getMetadata().entrySet()) {
246 if ("matchable".equals(entrySet.getKey()) && "true".equals(entrySet.getValue())) {
256 * generateMatchable - Given the object, generates list of MatchType objects and add them
257 * to the TargetType object.
259 * @param targetType TargetType object to add matches to
260 * @param key Property key
261 * @param value Object is the value - which can be a Collection or single Object
262 * @return TargetType incoming TargetType returned as a convenience
264 @SuppressWarnings("unchecked")
265 protected TargetType generateMatchable(TargetType targetType, String key, Object value) {
266 if (value instanceof Collection) {
267 AnyOfType anyOf = generateMatches((Collection<Object>) value,
268 new IdentifierImpl(ToscaDictionary.ID_RESOURCE_MATCHABLE + key));
269 if (! anyOf.getAllOf().isEmpty()) {
270 targetType.getAnyOf().add(anyOf);
273 AnyOfType anyOf = generateMatches(Arrays.asList(value),
274 new IdentifierImpl(ToscaDictionary.ID_RESOURCE_MATCHABLE + key));
275 if (! anyOf.getAllOf().isEmpty()) {
276 targetType.getAnyOf().add(anyOf);
283 * generateMatches - Goes through the collection of objects, creates a MatchType object
284 * for each object and associates it with the given attribute Id. Returns the AnyOfType
285 * object that contains all the generated MatchType objects.
287 * @param matchables Collection of object to generate MatchType from
288 * @param attributeId Given attribute Id for each MatchType
289 * @return AnyOfType object
291 protected AnyOfType generateMatches(Collection<Object> matchables, Identifier attributeId) {
293 // This is our outer AnyOf - which is an OR
295 AnyOfType anyOf = new AnyOfType();
296 for (Object matchable : matchables) {
300 Identifier idFunction = XACML3.ID_FUNCTION_STRING_EQUAL;
301 Identifier idDatatype = XACML3.ID_DATATYPE_STRING;
303 // See if we are another datatype
305 // We should add datetime support. But to do that we need
306 // probably more metadata to describe how that would be translated.
308 if (matchable instanceof Integer) {
309 idFunction = XACML3.ID_FUNCTION_INTEGER_EQUAL;
310 idDatatype = XACML3.ID_DATATYPE_INTEGER;
311 } else if (matchable instanceof Double) {
312 idFunction = XACML3.ID_FUNCTION_DOUBLE_EQUAL;
313 idDatatype = XACML3.ID_DATATYPE_DOUBLE;
314 } else if (matchable instanceof Boolean) {
315 idFunction = XACML3.ID_FUNCTION_BOOLEAN_EQUAL;
316 idDatatype = XACML3.ID_DATATYPE_BOOLEAN;
319 // Create a match for this
321 MatchType match = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
323 matchable.toString(),
326 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
328 // Now create an anyOf (OR)
330 anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(match));
336 * Get Policy Type definitions. This could be previously loaded, or could be
337 * stored in application path, or may need to be pulled from the API.
340 * @param policyTypeId Policy Type Id
341 * @return A list of PolicyTypes
343 private List<ToscaPolicyType> getPolicyTypes(ToscaPolicyTypeIdentifier policyTypeId) {
345 // Create identifier from the policy
347 ToscaPolicyTypeIdentifier typeId = new ToscaPolicyTypeIdentifier(policyTypeId);
349 // Find the Policy Type
351 ToscaPolicyType policyType = findPolicyType(typeId);
352 if (policyType == null) {
353 return Collections.emptyList();
356 // Create our return object
358 List<ToscaPolicyType> listTypes = new ArrayList<>();
359 listTypes.add(policyType);
361 // Look for parent policy types that could also contain matchable properties
363 ToscaPolicyType childPolicyType = policyType;
364 while (! childPolicyType.getDerivedFrom().startsWith("tosca.policies.Root")) {
366 // Create parent policy type id.
368 // We will have to assume the same version between child and the
369 // parent policy type it derives from.
371 // Or do we assume 1.0.0?
373 ToscaPolicyTypeIdentifier parentId = new ToscaPolicyTypeIdentifier(childPolicyType.getDerivedFrom(),
376 // Find the policy type
378 ToscaPolicyType parentPolicyType = findPolicyType(parentId);
379 if (parentPolicyType == null) {
381 // Probably would be best to throw an exception and
382 // return nothing back.
384 // But instead we will log a warning
386 LOGGER.warn("Missing parent policy type - proceeding anyway {}", parentId);
395 listTypes.add(parentPolicyType);
397 // Move to the next parent
399 childPolicyType = parentPolicyType;
405 * findPolicyType - given the ToscaPolicyTypeIdentifier, finds it in memory, or
406 * then tries to find it either locally on disk or pull it from the Policy
407 * Lifecycle API the given TOSCA Policy Type.
409 * @param policyTypeId ToscaPolicyTypeIdentifier to find
410 * @return ToscaPolicyType object. Can be null if failure.
412 private ToscaPolicyType findPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
414 // Is it loaded in memory?
416 ToscaPolicyType policyType = this.matchablePolicyTypes.get(policyTypeId);
417 if (policyType == null) {
421 policyType = this.loadPolicyType(policyTypeId);
430 * loadPolicyType - Tries to load the given ToscaPolicyTypeIdentifier from local
431 * storage. If it does not exist, will then attempt to pull from Policy Lifecycle
434 * @param policyTypeId ToscaPolicyTypeIdentifier input
435 * @return ToscaPolicyType object. Null if failure.
437 private ToscaPolicyType loadPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
439 // Construct what the file name should be
441 Path policyTypePath = this.constructLocalFilePath(policyTypeId);
448 // If it exists locally, read the bytes in
450 bytes = Files.readAllBytes(policyTypePath);
451 } catch (IOException e) {
453 // Does not exist locally, so let's GET it from the policy api
455 LOGGER.error("PolicyType not found in data area yet {}", policyTypePath, e);
457 // So let's pull it from API REST call and save it locally
459 return this.pullPolicyType(policyTypeId, policyTypePath);
462 // Success - we have read locally the policy type. Now bring it into our
465 LOGGER.info("Read in local policy type {}", policyTypePath.toAbsolutePath());
467 ToscaServiceTemplate serviceTemplate = standardYamlCoder.decode(new String(bytes, StandardCharsets.UTF_8),
468 ToscaServiceTemplate.class);
469 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
470 jtst.fromAuthorative(serviceTemplate);
471 ToscaServiceTemplate completedJtst = jtst.toAuthorative();
473 // Search for our Policy Type, there really only should be one but
474 // this is returned as a map.
476 for ( Entry<String, ToscaPolicyType> entrySet : completedJtst.getPolicyTypes().entrySet()) {
477 ToscaPolicyType entryPolicyType = entrySet.getValue();
478 if (policyTypeId.getName().equals(entryPolicyType.getName())
479 && policyTypeId.getVersion().equals(entryPolicyType.getVersion())) {
480 LOGGER.info("Found existing local policy type {} {}", entryPolicyType.getName(),
481 entryPolicyType.getVersion());
483 // Just simply return the policy type right here
485 return entryPolicyType;
487 LOGGER.warn("local policy type contains different name version {} {}", entryPolicyType.getName(),
488 entryPolicyType.getVersion());
492 // This would be an error, if the file stored does not match what its supposed to be
494 LOGGER.error("Existing policy type file does not contain right name and version");
495 } catch (CoderException e) {
496 LOGGER.error("Failed to decode tosca template for {}", policyTypePath, e);
499 // Hopefully we never get here
501 LOGGER.error("Failed to find/load policy type {}", policyTypeId);
506 * pullPolicyType - pulls the given ToscaPolicyTypeIdentifier from the Policy Lifecycle API.
507 * If successful, will store it locally given the policyTypePath.
509 * @param policyTypeId ToscaPolicyTypeIdentifier
510 * @param policyTypePath Path object to store locally
511 * @return ToscaPolicyType object. Null if failure.
513 private synchronized ToscaPolicyType pullPolicyType(ToscaPolicyTypeIdentifier policyTypeId, Path policyTypePath) {
515 // This is what we return
517 ToscaPolicyType policyType = null;
519 PolicyApiCaller api = new PolicyApiCaller(this.apiRestParameters);
521 policyType = api.getPolicyType(policyTypeId);
522 } catch (PolicyApiException e) {
523 LOGGER.error("Failed to make API call", e);
524 LOGGER.error("parameters: {} ", this.apiRestParameters);
531 standardYamlCoder.encode(policyTypePath.toFile(), policyType);
532 } catch (CoderException e) {
533 LOGGER.error("Failed to store {} locally to {}", policyTypeId, policyTypePath, e);
536 // Done return the policy type
542 * constructLocalFilePath - common method to ensure the name of the local file for the
543 * policy type is the same.
545 * @param policyTypeId ToscaPolicyTypeIdentifier
546 * @return Path object
548 private Path constructLocalFilePath(ToscaPolicyTypeIdentifier policyTypeId) {
549 return Paths.get(this.pathForData.toAbsolutePath().toString(), policyTypeId.getName() + "-"
550 + policyTypeId.getVersion() + ".yaml");