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(toscaPolicy.getType())
136 .convertPolicy(toscaPolicy);
137 if (xacmlPolicy == null) {
138 throw new ToscaPolicyConversionException("Failed to convert policy");
141 // Create a copy of the properties object
143 Properties newProperties = this.getProperties();
145 // Construct the filename
147 Path refPath = XacmlPolicyUtils.constructUniquePolicyFilename(xacmlPolicy, this.getDataPath());
149 // Write the policy to disk
150 // Maybe check for an error
152 XACMLPolicyWriter.writePolicyFile(refPath, xacmlPolicy);
153 if (LOGGER.isDebugEnabled()) {
154 LOGGER.debug("Xacml Policy is {}{}", System.lineSeparator(), new String(Files.readAllBytes(refPath)));
157 // Add root policy to properties object
159 XacmlPolicyUtils.addRootPolicy(newProperties, refPath);
161 // Write the properties to disk
163 XacmlPolicyUtils.storeXacmlProperties(newProperties,
164 XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
168 this.createEngine(newProperties);
170 // Save the properties
172 this.pdpProperties = newProperties;
176 this.mapLoadedPolicies.put(toscaPolicy, refPath);
177 } catch (IOException | ToscaPolicyConversionException e) {
178 LOGGER.error("Failed to loadPolicies {}", e);
185 public synchronized boolean unloadPolicy(ToscaPolicy toscaPolicy) throws XacmlApplicationException {
187 // Find it in our map
189 Path refPolicy = this.mapLoadedPolicies.get(toscaPolicy);
190 if (refPolicy == null) {
191 LOGGER.error("Failed to find ToscaPolicy {} in our map size {}", toscaPolicy.getMetadata(),
192 this.mapLoadedPolicies.size());
196 // Create a copy of the properties object
198 Properties newProperties = this.getProperties();
200 // Remove it from the properties
202 XacmlPolicyUtils.removeRootPolicy(newProperties, refPolicy);
204 // We can delete the file
207 Files.delete(refPolicy);
208 } catch (IOException e) {
209 LOGGER.error("Failed to delete policy {} from disk {}", toscaPolicy.getMetadata(),
210 refPolicy.toAbsolutePath().toString(), e);
213 // Write the properties to disk
216 XacmlPolicyUtils.storeXacmlProperties(newProperties,
217 XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
218 } catch (IOException e) {
219 LOGGER.error("Failed to save the properties to disk {}", newProperties);
224 this.createEngine(newProperties);
226 // Save the properties
228 this.pdpProperties = newProperties;
232 if (this.mapLoadedPolicies.remove(toscaPolicy) == null) {
233 LOGGER.error("Failed to remove toscaPolicy {} from internal map size {}", toscaPolicy.getMetadata(),
234 this.mapLoadedPolicies.size());
237 // Not sure if any of the errors above warrant returning false
243 public DecisionResponse makeDecision(DecisionRequest request) {
245 // Convert to a XacmlRequest
247 Request xacmlRequest = this.getTranslator().convertRequest(request);
249 // Now get a decision
251 Response xacmlResponse = this.xacmlDecision(xacmlRequest);
253 // Convert to a DecisionResponse
255 return this.getTranslator().convertResponse(xacmlResponse);
258 protected abstract ToscaPolicyTranslator getTranslator(String type);
260 protected ToscaPolicyTranslator getTranslator() {
261 return this.getTranslator("");
264 protected synchronized PDPEngine getEngine() {
265 return this.pdpEngine;
268 protected synchronized Properties getProperties() {
269 Properties newProperties = new Properties();
270 newProperties.putAll(pdpProperties);
271 return newProperties;
274 protected synchronized Path getDataPath() {
279 * Load properties from given file.
281 * @throws IOException If unable to read file
283 protected synchronized Properties loadXacmlProperties() throws IOException {
284 LOGGER.debug("Loading xacml properties {}", pathForData);
285 try (InputStream is = Files.newInputStream(pathForData)) {
286 Properties properties = new Properties();
293 * Stores the XACML Properties to the given file location.
295 * @throws IOException If unable to store the file.
297 protected synchronized void storeXacmlProperties() throws IOException {
298 try (OutputStream os = Files.newOutputStream(pathForData)) {
299 String strComments = "#";
300 pdpProperties.store(os, strComments);
305 * Appends 'xacml.properties' to a root Path object
307 * @return Path to rootPath/xacml.properties file
309 protected synchronized Path getPropertiesPath() {
310 return Paths.get(pathForData.toAbsolutePath().toString(), "xacml.properties");
314 * Creates an instance of PDP engine given the Properties object.
316 protected synchronized void createEngine(Properties properties) {
318 // Now initialize the XACML PDP Engine
321 PDPEngineFactory factory = PDPEngineFactory.newInstance();
322 PDPEngine engine = factory.newEngine(properties);
323 if (engine != null) {
324 this.pdpEngine = engine;
326 } catch (FactoryException e) {
327 LOGGER.error("Failed to create XACML PDP Engine {}", e);
332 * Make a decision call.
334 * @param request Incoming request object
335 * @return Response object
337 protected synchronized Response xacmlDecision(Request request) {
339 // This is what we need to return
341 Response response = null;
345 long timeStart = System.currentTimeMillis();
347 response = this.pdpEngine.decide(request);
348 } catch (PDPException e) {
349 LOGGER.error("Xacml PDP Engine failed {}", e);
352 // Track the end of timing
354 long timeEnd = System.currentTimeMillis();
355 LOGGER.info("Elapsed Time: {}ms", (timeEnd - timeStart));