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.charset.StandardCharsets;
34 import java.nio.file.Files;
35 import java.nio.file.Path;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.List;
40 import java.util.Properties;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
43 import org.apache.commons.lang3.tuple.Pair;
44 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
45 import org.onap.policy.models.decisions.concepts.DecisionRequest;
46 import org.onap.policy.models.decisions.concepts.DecisionResponse;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
49 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
50 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
51 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
52 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
53 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
57 public abstract class StdXacmlApplicationServiceProvider implements XacmlApplicationServiceProvider {
59 private static final Logger LOGGER = LoggerFactory.getLogger(StdXacmlApplicationServiceProvider.class);
60 private Path pathForData = null;
62 private RestServerParameters policyApiParameters;
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, RestServerParameters policyApiParameters)
83 throws XacmlApplicationException {
87 this.pathForData = pathForData;
88 LOGGER.info("New Path is {}", this.pathForData.toAbsolutePath());
92 this.policyApiParameters = policyApiParameters;
94 // Look for and load the properties object
97 pdpProperties = XacmlPolicyUtils.loadXacmlProperties(XacmlPolicyUtils.getPropertiesPath(pathForData));
98 LOGGER.info("{}", pdpProperties);
99 } catch (IOException e) {
100 throw new XacmlApplicationException("Failed to load " + XacmlPolicyUtils.XACML_PROPERTY_FILE, e);
105 createEngine(pdpProperties);
109 public List<ToscaPolicyTypeIdentifier> supportedPolicyTypes() {
110 throw new UnsupportedOperationException("Please override and implement supportedPolicyTypes");
114 public boolean canSupportPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
115 throw new UnsupportedOperationException("Please override and implement canSupportPolicyType");
119 public synchronized boolean loadPolicy(ToscaPolicy toscaPolicy) {
122 // Convert the policies first
124 PolicyType xacmlPolicy = this.getTranslator(toscaPolicy.getType())
125 .convertPolicy(toscaPolicy);
126 if (xacmlPolicy == null) {
127 throw new ToscaPolicyConversionException("Failed to convert policy");
130 // Create a copy of the properties object
132 Properties newProperties = this.getProperties();
134 // Construct the filename
136 Path refPath = XacmlPolicyUtils.constructUniquePolicyFilename(xacmlPolicy, this.getDataPath());
138 // Write the policy to disk
139 // Maybe check for an error
141 XACMLPolicyWriter.writePolicyFile(refPath, xacmlPolicy);
142 if (LOGGER.isInfoEnabled()) {
143 LOGGER.info("Xacml Policy is {}{}", XacmlPolicyUtils.LINE_SEPARATOR,
144 new String(Files.readAllBytes(refPath), StandardCharsets.UTF_8));
147 // Add root policy to properties object
149 XacmlPolicyUtils.addRootPolicy(newProperties, refPath);
151 // Write the properties to disk
153 XacmlPolicyUtils.storeXacmlProperties(newProperties,
154 XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
158 this.createEngine(newProperties);
160 // Save the properties
162 this.pdpProperties = newProperties;
166 this.mapLoadedPolicies.put(toscaPolicy, refPath);
167 } catch (IOException | ToscaPolicyConversionException e) {
168 LOGGER.error("Failed to loadPolicies {}", e);
175 public synchronized boolean unloadPolicy(ToscaPolicy toscaPolicy) throws XacmlApplicationException {
177 // Find it in our map
179 Path refPolicy = this.mapLoadedPolicies.get(toscaPolicy);
180 if (refPolicy == null) {
181 LOGGER.error("Failed to find ToscaPolicy {} in our map size {}", toscaPolicy.getMetadata(),
182 this.mapLoadedPolicies.size());
186 // Create a copy of the properties object
188 Properties newProperties = this.getProperties();
190 // Remove it from the properties
192 XacmlPolicyUtils.removeRootPolicy(newProperties, refPolicy);
194 // We can delete the file
197 Files.delete(refPolicy);
198 } catch (IOException e) {
199 LOGGER.error("Failed to delete policy {} from disk {}", toscaPolicy.getMetadata(),
200 refPolicy.toAbsolutePath().toString(), e);
203 // Write the properties to disk
206 XacmlPolicyUtils.storeXacmlProperties(newProperties,
207 XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
208 } catch (IOException e) {
209 LOGGER.error("Failed to save the properties to disk {}", newProperties, e);
214 this.createEngine(newProperties);
216 // Save the properties
218 this.pdpProperties = newProperties;
222 if (this.mapLoadedPolicies.remove(toscaPolicy) == null) {
223 LOGGER.error("Failed to remove toscaPolicy {} from internal map size {}", toscaPolicy.getMetadata(),
224 this.mapLoadedPolicies.size());
227 // Not sure if any of the errors above warrant returning false
233 public Pair<DecisionResponse, Response> makeDecision(DecisionRequest request,
234 Map<String, String[]> requestQueryParams) {
236 // Convert to a XacmlRequest
238 Request xacmlRequest = this.getTranslator().convertRequest(request);
240 // Now get a decision
242 Response xacmlResponse = this.xacmlDecision(xacmlRequest);
244 // Convert to a DecisionResponse
246 return Pair.of(this.getTranslator().convertResponse(xacmlResponse), xacmlResponse);
249 protected abstract ToscaPolicyTranslator getTranslator(String type);
251 protected ToscaPolicyTranslator getTranslator() {
252 return this.getTranslator("");
255 protected synchronized PDPEngine getEngine() {
256 return this.pdpEngine;
259 protected synchronized Properties getProperties() {
260 Properties newProperties = new Properties();
261 newProperties.putAll(pdpProperties);
262 return newProperties;
265 protected synchronized Path getDataPath() {
270 * Creates an instance of PDP engine given the Properties object.
272 protected synchronized void createEngine(Properties properties) {
274 // Now initialize the XACML PDP Engine
277 PDPEngineFactory factory = getPdpEngineFactory();
278 PDPEngine engine = factory.newEngine(properties);
279 if (engine != null) {
280 this.pdpEngine = engine;
282 } catch (FactoryException e) {
283 LOGGER.error("Failed to create XACML PDP Engine {}", e);
288 * Make a decision call.
290 * @param request Incoming request object
291 * @return Response object
293 protected synchronized Response xacmlDecision(Request request) {
295 // This is what we need to return
297 Response response = null;
301 long timeStart = System.currentTimeMillis();
303 response = this.pdpEngine.decide(request);
304 } catch (PDPException e) {
305 LOGGER.error("Xacml PDP Engine failed {}", e);
308 // Track the end of timing
310 long timeEnd = System.currentTimeMillis();
311 LOGGER.info("Elapsed Time: {}ms", (timeEnd - timeStart));
316 // these may be overridden by junit tests
318 protected PDPEngineFactory getPdpEngineFactory() throws FactoryException {
319 return PDPEngineFactory.newInstance();