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;
32 import java.io.IOException;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.List;
39 import java.util.Properties;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
42 import org.apache.commons.lang3.tuple.Pair;
43 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
44 import org.onap.policy.models.decisions.concepts.DecisionRequest;
45 import org.onap.policy.models.decisions.concepts.DecisionResponse;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
48 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
49 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
50 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
51 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
52 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
56 public abstract class StdXacmlApplicationServiceProvider implements XacmlApplicationServiceProvider {
58 private static final Logger LOGGER = LoggerFactory.getLogger(StdXacmlApplicationServiceProvider.class);
59 private Path pathForData = null;
61 private RestServerParameters policyApiParameters;
62 private Properties pdpProperties = null;
63 private PDPEngine pdpEngine = null;
64 private Map<ToscaPolicy, Path> mapLoadedPolicies = new HashMap<>();
66 public StdXacmlApplicationServiceProvider() {
71 public String applicationName() {
72 return "Please Override";
76 public List<String> actionDecisionsSupported() {
77 return Collections.emptyList();
81 public void initialize(Path pathForData, RestServerParameters policyApiParameters)
82 throws XacmlApplicationException {
86 this.pathForData = pathForData;
87 LOGGER.info("New Path is {}", this.pathForData.toAbsolutePath());
91 this.policyApiParameters = policyApiParameters;
93 // Look for and load the properties object
96 pdpProperties = XacmlPolicyUtils.loadXacmlProperties(XacmlPolicyUtils.getPropertiesPath(pathForData));
97 LOGGER.info("{}", pdpProperties);
98 } catch (IOException e) {
99 throw new XacmlApplicationException("Failed to load " + XacmlPolicyUtils.XACML_PROPERTY_FILE, e);
104 createEngine(pdpProperties);
108 public List<ToscaPolicyTypeIdentifier> supportedPolicyTypes() {
109 throw new UnsupportedOperationException("Please override and implement supportedPolicyTypes");
113 public boolean canSupportPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
114 throw new UnsupportedOperationException("Please override and implement canSupportPolicyType");
118 public synchronized boolean loadPolicy(ToscaPolicy toscaPolicy) {
121 // Convert the policies first
123 PolicyType xacmlPolicy = this.getTranslator(toscaPolicy.getType())
124 .convertPolicy(toscaPolicy);
125 if (xacmlPolicy == null) {
126 throw new ToscaPolicyConversionException("Failed to convert policy");
129 // Create a copy of the properties object
131 Properties newProperties = this.getProperties();
133 // Construct the filename
135 Path refPath = XacmlPolicyUtils.constructUniquePolicyFilename(xacmlPolicy, this.getDataPath());
137 // Write the policy to disk
138 // Maybe check for an error
140 XACMLPolicyWriter.writePolicyFile(refPath, xacmlPolicy);
141 if (LOGGER.isInfoEnabled()) {
142 LOGGER.info("Xacml Policy is {}{}", System.lineSeparator(), new String(Files.readAllBytes(refPath)));
145 // Add root policy to properties object
147 XacmlPolicyUtils.addRootPolicy(newProperties, refPath);
149 // Write the properties to disk
151 XacmlPolicyUtils.storeXacmlProperties(newProperties,
152 XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
156 this.createEngine(newProperties);
158 // Save the properties
160 this.pdpProperties = newProperties;
164 this.mapLoadedPolicies.put(toscaPolicy, refPath);
165 } catch (IOException | ToscaPolicyConversionException e) {
166 LOGGER.error("Failed to loadPolicies {}", e);
173 public synchronized boolean unloadPolicy(ToscaPolicy toscaPolicy) throws XacmlApplicationException {
175 // Find it in our map
177 Path refPolicy = this.mapLoadedPolicies.get(toscaPolicy);
178 if (refPolicy == null) {
179 LOGGER.error("Failed to find ToscaPolicy {} in our map size {}", toscaPolicy.getMetadata(),
180 this.mapLoadedPolicies.size());
184 // Create a copy of the properties object
186 Properties newProperties = this.getProperties();
188 // Remove it from the properties
190 XacmlPolicyUtils.removeRootPolicy(newProperties, refPolicy);
192 // We can delete the file
195 Files.delete(refPolicy);
196 } catch (IOException e) {
197 LOGGER.error("Failed to delete policy {} from disk {}", toscaPolicy.getMetadata(),
198 refPolicy.toAbsolutePath().toString(), e);
201 // Write the properties to disk
204 XacmlPolicyUtils.storeXacmlProperties(newProperties,
205 XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
206 } catch (IOException e) {
207 LOGGER.error("Failed to save the properties to disk {}", newProperties, e);
212 this.createEngine(newProperties);
214 // Save the properties
216 this.pdpProperties = newProperties;
220 if (this.mapLoadedPolicies.remove(toscaPolicy) == null) {
221 LOGGER.error("Failed to remove toscaPolicy {} from internal map size {}", toscaPolicy.getMetadata(),
222 this.mapLoadedPolicies.size());
225 // Not sure if any of the errors above warrant returning false
231 public Pair<DecisionResponse, Response> makeDecision(DecisionRequest request) {
233 // Convert to a XacmlRequest
235 Request xacmlRequest = this.getTranslator().convertRequest(request);
237 // Now get a decision
239 Response xacmlResponse = this.xacmlDecision(xacmlRequest);
241 // Convert to a DecisionResponse
243 return Pair.of(this.getTranslator().convertResponse(xacmlResponse), xacmlResponse);
246 protected abstract ToscaPolicyTranslator getTranslator(String type);
248 protected ToscaPolicyTranslator getTranslator() {
249 return this.getTranslator("");
252 protected synchronized PDPEngine getEngine() {
253 return this.pdpEngine;
256 protected synchronized Properties getProperties() {
257 Properties newProperties = new Properties();
258 newProperties.putAll(pdpProperties);
259 return newProperties;
262 protected synchronized Path getDataPath() {
267 * Creates an instance of PDP engine given the Properties object.
269 protected synchronized void createEngine(Properties properties) {
271 // Now initialize the XACML PDP Engine
274 PDPEngineFactory factory = getPdpEngineFactory();
275 PDPEngine engine = factory.newEngine(properties);
276 if (engine != null) {
277 this.pdpEngine = engine;
279 } catch (FactoryException e) {
280 LOGGER.error("Failed to create XACML PDP Engine {}", e);
285 * Make a decision call.
287 * @param request Incoming request object
288 * @return Response object
290 protected synchronized Response xacmlDecision(Request request) {
292 // This is what we need to return
294 Response response = null;
298 long timeStart = System.currentTimeMillis();
300 response = this.pdpEngine.decide(request);
301 } catch (PDPException e) {
302 LOGGER.error("Xacml PDP Engine failed {}", e);
305 // Track the end of timing
307 long timeEnd = System.currentTimeMillis();
308 LOGGER.info("Elapsed Time: {}ms", (timeEnd - timeStart));
313 // these may be overridden by junit tests
315 protected PDPEngineFactory getPdpEngineFactory() throws FactoryException {
316 return PDPEngineFactory.newInstance();