Update snapshot and/or references of policy/xacml-pdp to latest snapshots
[policy/xacml-pdp.git] / applications / guard / src / main / java / org / onap / policy / xacml / pdp / application / guard / CoordinationGuardTranslator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019-2021 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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.xacml.pdp.application.guard;
24
25 import com.att.research.xacml.api.Request;
26 import com.att.research.xacml.api.Response;
27 import com.att.research.xacml.util.XACMLPolicyScanner;
28 import java.io.ByteArrayInputStream;
29 import java.io.File;
30 import java.io.FileInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.nio.charset.StandardCharsets;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.UUID;
37 import lombok.NoArgsConstructor;
38 import org.apache.commons.io.IOUtils;
39 import org.onap.policy.common.utils.coder.CoderException;
40 import org.onap.policy.common.utils.coder.StandardYamlCoder;
41 import org.onap.policy.common.utils.resources.ResourceUtils;
42 import org.onap.policy.models.decisions.concepts.DecisionRequest;
43 import org.onap.policy.models.decisions.concepts.DecisionResponse;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
45 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
46 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 @NoArgsConstructor
51 public class CoordinationGuardTranslator implements ToscaPolicyTranslator {
52
53     private static final Logger LOGGER = LoggerFactory.getLogger(CoordinationGuardTranslator.class);
54
55     @Override
56     public Object convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
57         LOGGER.debug("Using CoordinationGuardTranslator.convertPolicy");
58         //
59         // Policy name should be at the root
60         //
61         String type = toscaPolicy.getType();
62         var coordinationFunctionPath = "coordination/function";
63         Map<String, Object> policyProps = toscaPolicy.getProperties();
64         LOGGER.debug("path = {}", coordinationFunctionPath);
65         LOGGER.debug("props = {}", policyProps);
66         @SuppressWarnings("unchecked")
67         List<String> controlLoop = (List<String>) policyProps.get("controlLoop");
68         var cd = new CoordinationDirective();
69         cd.setCoordinationFunction(type);
70         cd.setControlLoop(controlLoop);
71         LOGGER.debug("CoordinationDirective = {}", cd);
72         //
73         // Generate the xacml policy as a string
74         //
75         String xacmlStr = generateXacmlFromCoordinationDirective(cd, coordinationFunctionPath);
76         LOGGER.debug("xacmlStr\n{}", xacmlStr);
77         //
78         // Scan the string and convert to PoilcyType
79         //
80         try (InputStream is = new ByteArrayInputStream(xacmlStr.getBytes(StandardCharsets.UTF_8))) {
81             return XACMLPolicyScanner.readPolicy(is);
82         } catch (IOException e) {
83             throw new ToscaPolicyConversionException("Failed to read policy", e);
84         }
85     }
86
87     /**
88      * This function is not used for CLC instead
89      * the one in LegacyGuardTranslator is used.
90      */
91     @Override
92     public Request convertRequest(DecisionRequest request) throws ToscaPolicyConversionException {
93         throw new ToscaPolicyConversionException("this convertRequest shouldn't be used");
94     }
95
96     /**
97      * This function is not used for CLC instead
98      * the one in LegacyGuardTranslator is used.
99      */
100     @Override
101     public DecisionResponse convertResponse(Response xacmlResponse) {
102         LOGGER.info("this convertResponse shouldn't be used");
103         return null;
104     }
105
106     /**
107      * Load YAML coordination directive.
108      *
109      * @param directiveFilename yaml directive file to load
110      * @return the CoordinationDirective
111      */
112     public static CoordinationDirective loadCoordinationDirectiveFromFile(
113         String directiveFilename) {
114         if (directiveFilename == null) {
115             return null;
116         }
117         try (InputStream is = new FileInputStream(new File(directiveFilename))) {
118             var contents = IOUtils.toString(is, StandardCharsets.UTF_8);
119             //
120             // Read the yaml into our Java Object
121             //
122             CoordinationDirective obj =
123                 new StandardYamlCoder().decode(contents, CoordinationDirective.class);
124             LOGGER.debug(contents);
125             return obj;
126         } catch (IOException | CoderException e) {
127             LOGGER.error("Error while loading YAML coordination directive", e);
128         }
129         return null;
130     }
131
132     /**
133      * Generate Xacml rule implementing specified CoordinationDirective.
134      *
135      * @param cd the CoordinationDirective
136      * @param protoDir the directory containing Xacml implementation prototypes
137      * @return the generated Xacml policy
138      */
139     public static String generateXacmlFromCoordinationDirective(CoordinationDirective cd,
140         String protoDir) throws ToscaPolicyConversionException {
141         /*
142          * Determine file names
143          */
144         String xacmlProtoFilename =
145             protoDir + File.separator + cd.getCoordinationFunction() + ".xml";
146         LOGGER.info("xacmlProtoFilename={}", xacmlProtoFilename);
147         /*
148          * Values to be substituted for placeholder's
149          */
150         final var uniqueId = UUID.randomUUID().toString();
151         final String cLOne = cd.getControlLoop(0);
152         final String cLTwo = cd.getControlLoop(1);
153         /*
154          * Replace function placeholder's with appropriate values
155          */
156         var policyXml = ResourceUtils.getResourceAsString(xacmlProtoFilename);
157         if (policyXml == null) {
158             throw new ToscaPolicyConversionException("Unable to find prototype " + xacmlProtoFilename);
159         }
160         policyXml = policyXml.replace("UNIQUE_ID", uniqueId);
161         policyXml = policyXml.replace("CONTROL_LOOP_ONE", cLOne);
162         policyXml = policyXml.replace("CONTROL_LOOP_TWO", cLTwo);
163
164         return policyXml;
165
166     }
167
168 }