Changes to handle PDPX deploy/undeploy
[policy/xacml-pdp.git] / applications / common / src / main / java / org / onap / policy / pdp / xacml / application / common / std / StdXacmlApplicationServiceProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
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
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.pdp.xacml.application.common.std;
24
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
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;
42 import java.util.Map;
43 import java.util.Properties;
44
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
46
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;
58
59 public abstract class StdXacmlApplicationServiceProvider implements XacmlApplicationServiceProvider {
60
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<>();
66
67     public StdXacmlApplicationServiceProvider() {
68         super();
69     }
70
71     @Override
72     public String applicationName() {
73         return "Please Override";
74     }
75
76     @Override
77     public List<String> actionDecisionsSupported() {
78         return Collections.emptyList();
79     }
80
81     @Override
82     public void initialize(Path pathForData) throws XacmlApplicationException {
83         //
84         // Save our path
85         //
86         this.pathForData = pathForData;
87         LOGGER.info("New Path is {}", this.pathForData.toAbsolutePath());
88         //
89         // Ensure properties exist
90         //
91         Path propertiesPath = XacmlPolicyUtils.getPropertiesPath(pathForData);
92         if (! propertiesPath.toFile().exists()) {
93             LOGGER.info("Copying src/main/resources/xacml.properties to path");
94             //
95             // Properties do not exist, by default we will copy ours over
96             // from src/main/resources
97             //
98             try {
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);
102             }
103         }
104         //
105         // Look for and load the properties object
106         //
107         try {
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);
112         }
113         //
114         // Create an engine
115         //
116         createEngine(pdpProperties);
117     }
118
119     @Override
120     public List<ToscaPolicyTypeIdentifier> supportedPolicyTypes() {
121         throw new UnsupportedOperationException("Please override and implement supportedPolicyTypes");
122     }
123
124     @Override
125     public boolean canSupportPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
126         throw new UnsupportedOperationException("Please override and implement canSupportPolicyType");
127     }
128
129     @Override
130     public synchronized boolean loadPolicy(ToscaPolicy toscaPolicy) {
131         try {
132             //
133             // Convert the policies first
134             //
135             PolicyType xacmlPolicy = this.getTranslator().convertPolicy(toscaPolicy);
136             if (xacmlPolicy == null) {
137                 throw new ToscaPolicyConversionException("Failed to convert policy");
138             }
139             //
140             // Create a copy of the properties object
141             //
142             Properties newProperties = this.getProperties();
143             //
144             // Construct the filename
145             //
146             Path refPath = XacmlPolicyUtils.constructUniquePolicyFilename(xacmlPolicy, this.getDataPath());
147             //
148             // Write the policy to disk
149             // Maybe check for an error
150             //
151             XACMLPolicyWriter.writePolicyFile(refPath, xacmlPolicy);
152             if (LOGGER.isDebugEnabled()) {
153                 LOGGER.debug("Xacml Policy is {}{}", System.lineSeparator(), new String(Files.readAllBytes(refPath)));
154             }
155             //
156             // Add root policy to properties object
157             //
158             XacmlPolicyUtils.addRootPolicy(newProperties, refPath);
159             //
160             // Write the properties to disk
161             //
162             XacmlPolicyUtils.storeXacmlProperties(newProperties,
163                     XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
164             //
165             // Reload the engine
166             //
167             this.createEngine(newProperties);
168             //
169             // Save the properties
170             //
171             this.pdpProperties = newProperties;
172             //
173             // Save in our map
174             //
175             this.mapLoadedPolicies.put(toscaPolicy, refPath);
176         } catch (IOException | ToscaPolicyConversionException e) {
177             LOGGER.error("Failed to loadPolicies {}", e);
178             return false;
179         }
180         return true;
181     }
182
183     @Override
184     public synchronized boolean unloadPolicy(ToscaPolicy toscaPolicy) throws XacmlApplicationException {
185         //
186         // Find it in our map
187         //
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());
192             return false;
193         }
194         //
195         // Create a copy of the properties object
196         //
197         Properties newProperties = this.getProperties();
198         //
199         // Remove it from the properties
200         //
201         XacmlPolicyUtils.removeRootPolicy(newProperties, refPolicy);
202         //
203         // We can delete the file
204         //
205         try {
206             Files.delete(refPolicy);
207         } catch (IOException e) {
208             LOGGER.error("Failed to delete policy {} from disk {}", toscaPolicy.getMetadata(),
209                     refPolicy.toAbsolutePath().toString(), e);
210         }
211         //
212         // Write the properties to disk
213         //
214         try {
215             XacmlPolicyUtils.storeXacmlProperties(newProperties,
216                     XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
217         } catch (IOException e) {
218             LOGGER.error("Failed to save the properties to disk {}", newProperties);
219         }
220         //
221         // Reload the engine
222         //
223         this.createEngine(newProperties);
224         //
225         // Save the properties
226         //
227         this.pdpProperties = newProperties;
228         //
229         // Save in our map
230         //
231         if (this.mapLoadedPolicies.remove(toscaPolicy) == null) {
232             LOGGER.error("Failed to remove toscaPolicy {} from internal map size {}", toscaPolicy.getMetadata(),
233                     this.mapLoadedPolicies.size());
234         }
235         //
236         // Not sure if any of the errors above warrant returning false
237         //
238         return true;
239     }
240
241     @Override
242     public DecisionResponse makeDecision(DecisionRequest request) {
243         //
244         // Convert to a XacmlRequest
245         //
246         Request xacmlRequest = this.getTranslator().convertRequest(request);
247         //
248         // Now get a decision
249         //
250         Response xacmlResponse = this.xacmlDecision(xacmlRequest);
251         //
252         // Convert to a DecisionResponse
253         //
254         return this.getTranslator().convertResponse(xacmlResponse);
255     }
256
257
258     protected abstract ToscaPolicyTranslator getTranslator();
259
260     protected synchronized PDPEngine getEngine() {
261         return this.pdpEngine;
262     }
263
264     protected synchronized Properties getProperties() {
265         Properties newProperties = new Properties();
266         newProperties.putAll(pdpProperties);
267         return newProperties;
268     }
269
270     protected synchronized Path getDataPath() {
271         return pathForData;
272     }
273
274     /**
275      * Load properties from given file.
276      *
277      * @throws IOException If unable to read file
278      */
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();
283             properties.load(is);
284             return properties;
285         }
286     }
287
288     /**
289      * Stores the XACML Properties to the given file location.
290      *
291      * @throws IOException If unable to store the file.
292      */
293     protected synchronized void storeXacmlProperties() throws IOException {
294         try (OutputStream os = Files.newOutputStream(pathForData)) {
295             String strComments = "#";
296             pdpProperties.store(os, strComments);
297         }
298     }
299
300     /**
301      * Appends 'xacml.properties' to a root Path object
302      *
303      * @return Path to rootPath/xacml.properties file
304      */
305     protected synchronized Path getPropertiesPath() {
306         return Paths.get(pathForData.toAbsolutePath().toString(), "xacml.properties");
307     }
308
309     /**
310      * Creates an instance of PDP engine given the Properties object.
311      */
312     protected synchronized void createEngine(Properties properties) {
313         //
314         // Now initialize the XACML PDP Engine
315         //
316         try {
317             PDPEngineFactory factory = PDPEngineFactory.newInstance();
318             PDPEngine engine = factory.newEngine(properties);
319             if (engine != null) {
320                 this.pdpEngine = engine;
321             }
322         } catch (FactoryException e) {
323             LOGGER.error("Failed to create XACML PDP Engine {}", e);
324         }
325     }
326
327     /**
328      * Make a decision call.
329      *
330      * @param request Incoming request object
331      * @return Response object
332      */
333     protected synchronized Response xacmlDecision(Request request) {
334         //
335         // This is what we need to return
336         //
337         Response response = null;
338         //
339         // Track some timing
340         //
341         long timeStart = System.currentTimeMillis();
342         try {
343             response = this.pdpEngine.decide(request);
344         } catch (PDPException e) {
345             LOGGER.error("Xacml PDP Engine failed {}", e);
346         } finally {
347             //
348             // Track the end of timing
349             //
350             long timeEnd = System.currentTimeMillis();
351             LOGGER.info("Elapsed Time: {}ms", (timeEnd - timeStart));
352         }
353         return response;
354     }
355
356 }