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.Request;
26 import com.att.research.xacml.api.Response;
27 import com.att.research.xacml.api.pdp.PDPEngine;
28 import com.att.research.xacml.api.pdp.PDPEngineFactory;
29 import com.att.research.xacml.api.pdp.PDPException;
30 import com.att.research.xacml.util.FactoryException;
31 import com.att.research.xacml.util.XACMLPolicyWriter;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.OutputStream;
36 import java.nio.file.Files;
37 import java.nio.file.Path;
38 import java.nio.file.Paths;
39 import java.util.Collections;
40 import java.util.HashMap;
41 import java.util.List;
43 import java.util.Properties;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
47 import org.onap.policy.models.decisions.concepts.DecisionRequest;
48 import org.onap.policy.models.decisions.concepts.DecisionResponse;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
51 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
52 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
53 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
54 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
55 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 public abstract class StdXacmlApplicationServiceProvider implements XacmlApplicationServiceProvider {
61 private static final Logger LOGGER = LoggerFactory.getLogger(StdXacmlApplicationServiceProvider.class);
62 private Path pathForData = null;
63 private Properties pdpProperties = null;
64 private PDPEngine pdpEngine = null;
65 private Map<ToscaPolicy, Path> mapLoadedPolicies = new HashMap<>();
67 public StdXacmlApplicationServiceProvider() {
72 public String applicationName() {
73 return "Please Override";
77 public List<String> actionDecisionsSupported() {
78 return Collections.emptyList();
82 public void initialize(Path pathForData) throws XacmlApplicationException {
86 this.pathForData = pathForData;
87 LOGGER.info("New Path is {}", this.pathForData.toAbsolutePath());
89 // Ensure properties exist
91 Path propertiesPath = XacmlPolicyUtils.getPropertiesPath(pathForData);
92 if (! propertiesPath.toFile().exists()) {
93 LOGGER.info("Copying src/main/resources/xacml.properties to path");
95 // Properties do not exist, by default we will copy ours over
96 // from src/main/resources
99 Files.copy(Paths.get("src/main/resources/xacml.properties"), propertiesPath);
100 } catch (IOException e) {
101 throw new XacmlApplicationException("Failed to copy xacml.propertis", e);
105 // Look for and load the properties object
108 pdpProperties = XacmlPolicyUtils.loadXacmlProperties(XacmlPolicyUtils.getPropertiesPath(pathForData));
109 LOGGER.debug("{}", pdpProperties);
110 } catch (IOException e) {
111 throw new XacmlApplicationException("Failed to load xacml.propertis", e);
116 createEngine(pdpProperties);
120 public List<ToscaPolicyTypeIdentifier> supportedPolicyTypes() {
121 throw new UnsupportedOperationException("Please override and implement supportedPolicyTypes");
125 public boolean canSupportPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
126 throw new UnsupportedOperationException("Please override and implement canSupportPolicyType");
130 public synchronized boolean loadPolicy(ToscaPolicy toscaPolicy) {
133 // Convert the policies first
135 PolicyType xacmlPolicy = this.getTranslator().convertPolicy(toscaPolicy);
136 if (xacmlPolicy == null) {
137 throw new ToscaPolicyConversionException("Failed to convert policy");
140 // Create a copy of the properties object
142 Properties newProperties = this.getProperties();
144 // Construct the filename
146 Path refPath = XacmlPolicyUtils.constructUniquePolicyFilename(xacmlPolicy, this.getDataPath());
148 // Write the policy to disk
149 // Maybe check for an error
151 XACMLPolicyWriter.writePolicyFile(refPath, xacmlPolicy);
152 if (LOGGER.isDebugEnabled()) {
153 LOGGER.debug("Xacml Policy is {}{}", System.lineSeparator(), new String(Files.readAllBytes(refPath)));
156 // Add root policy to properties object
158 XacmlPolicyUtils.addRootPolicy(newProperties, refPath);
160 // Write the properties to disk
162 XacmlPolicyUtils.storeXacmlProperties(newProperties,
163 XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
167 this.createEngine(newProperties);
169 // Save the properties
171 this.pdpProperties = newProperties;
175 this.mapLoadedPolicies.put(toscaPolicy, refPath);
176 } catch (IOException | ToscaPolicyConversionException e) {
177 LOGGER.error("Failed to loadPolicies {}", e);
184 public synchronized boolean unloadPolicy(ToscaPolicy toscaPolicy) throws XacmlApplicationException {
186 // Find it in our map
188 Path refPolicy = this.mapLoadedPolicies.get(toscaPolicy);
189 if (refPolicy == null) {
190 LOGGER.error("Failed to find ToscaPolicy {} in our map size {}", toscaPolicy.getMetadata(),
191 this.mapLoadedPolicies.size());
195 // Create a copy of the properties object
197 Properties newProperties = this.getProperties();
199 // Remove it from the properties
201 XacmlPolicyUtils.removeRootPolicy(newProperties, refPolicy);
203 // We can delete the file
206 Files.delete(refPolicy);
207 } catch (IOException e) {
208 LOGGER.error("Failed to delete policy {} from disk {}", toscaPolicy.getMetadata(),
209 refPolicy.toAbsolutePath().toString(), e);
212 // Write the properties to disk
215 XacmlPolicyUtils.storeXacmlProperties(newProperties,
216 XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
217 } catch (IOException e) {
218 LOGGER.error("Failed to save the properties to disk {}", newProperties);
223 this.createEngine(newProperties);
225 // Save the properties
227 this.pdpProperties = newProperties;
231 if (this.mapLoadedPolicies.remove(toscaPolicy) == null) {
232 LOGGER.error("Failed to remove toscaPolicy {} from internal map size {}", toscaPolicy.getMetadata(),
233 this.mapLoadedPolicies.size());
236 // Not sure if any of the errors above warrant returning false
242 public DecisionResponse makeDecision(DecisionRequest request) {
244 // Convert to a XacmlRequest
246 Request xacmlRequest = this.getTranslator().convertRequest(request);
248 // Now get a decision
250 Response xacmlResponse = this.xacmlDecision(xacmlRequest);
252 // Convert to a DecisionResponse
254 return this.getTranslator().convertResponse(xacmlResponse);
258 protected abstract ToscaPolicyTranslator getTranslator();
260 protected synchronized PDPEngine getEngine() {
261 return this.pdpEngine;
264 protected synchronized Properties getProperties() {
265 Properties newProperties = new Properties();
266 newProperties.putAll(pdpProperties);
267 return newProperties;
270 protected synchronized Path getDataPath() {
275 * Load properties from given file.
277 * @throws IOException If unable to read file
279 protected synchronized Properties loadXacmlProperties() throws IOException {
280 LOGGER.debug("Loading xacml properties {}", pathForData);
281 try (InputStream is = Files.newInputStream(pathForData)) {
282 Properties properties = new Properties();
289 * Stores the XACML Properties to the given file location.
291 * @throws IOException If unable to store the file.
293 protected synchronized void storeXacmlProperties() throws IOException {
294 try (OutputStream os = Files.newOutputStream(pathForData)) {
295 String strComments = "#";
296 pdpProperties.store(os, strComments);
301 * Appends 'xacml.properties' to a root Path object
303 * @return Path to rootPath/xacml.properties file
305 protected synchronized Path getPropertiesPath() {
306 return Paths.get(pathForData.toAbsolutePath().toString(), "xacml.properties");
310 * Creates an instance of PDP engine given the Properties object.
312 protected synchronized void createEngine(Properties properties) {
314 // Now initialize the XACML PDP Engine
317 PDPEngineFactory factory = PDPEngineFactory.newInstance();
318 PDPEngine engine = factory.newEngine(properties);
319 if (engine != null) {
320 this.pdpEngine = engine;
322 } catch (FactoryException e) {
323 LOGGER.error("Failed to create XACML PDP Engine {}", e);
328 * Make a decision call.
330 * @param request Incoming request object
331 * @return Response object
333 protected synchronized Response xacmlDecision(Request request) {
335 // This is what we need to return
337 Response response = null;
341 long timeStart = System.currentTimeMillis();
343 response = this.pdpEngine.decide(request);
344 } catch (PDPException e) {
345 LOGGER.error("Xacml PDP Engine failed {}", e);
348 // Track the end of timing
350 long timeEnd = System.currentTimeMillis();
351 LOGGER.info("Elapsed Time: {}ms", (timeEnd - timeStart));