Test decision from main entry
[policy/xacml-pdp.git] / applications / monitoring / src / main / java / org / onap / policy / xacml / pdp / application / monitoring / MonitoringPdpApplication.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.xacml.pdp.application.monitoring;
24
25 import com.att.research.xacml.api.Request;
26 import com.att.research.xacml.api.Response;
27 import com.att.research.xacml.util.XACMLPolicyScanner;
28 import com.att.research.xacml.util.XACMLPolicyWriter;
29 import com.att.research.xacml.util.XACMLProperties;
30
31 import java.io.ByteArrayOutputStream;
32 import java.io.FileInputStream;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.nio.file.Path;
36 import java.nio.file.Paths;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Properties;
42 import java.util.Set;
43
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
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.ToscaPolicyTypeIdentifier;
50 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
51 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
52 import org.onap.policy.pdp.xacml.application.common.std.StdCombinedPolicyResultsTranslator;
53 import org.onap.policy.pdp.xacml.application.common.std.StdXacmlApplicationServiceProvider;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 /**
58  * This is the engine class that manages the instance of the XACML PDP engine.
59  *
60  * <p>It is responsible for initializing it and shutting it down properly in a thread-safe manner.
61  *
62  *
63  * @author pameladragosh
64  *
65  */
66 public class MonitoringPdpApplication extends StdXacmlApplicationServiceProvider {
67
68     private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPdpApplication.class);
69     private static final String ONAP_MONITORING_BASE_POLICY_TYPE = "onap.Monitoring";
70     private static final String ONAP_MONITORING_DERIVED_POLICY_TYPE = "onap.policies.monitoring";
71
72     private StdCombinedPolicyResultsTranslator translator = new StdCombinedPolicyResultsTranslator();
73     private List<ToscaPolicyTypeIdentifier> supportedPolicyTypes = new ArrayList<>();
74
75     /**
76      * Constructor.
77      */
78     public MonitoringPdpApplication() {
79         //
80         // By default this supports just Monitoring policy types
81         //
82         supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(ONAP_MONITORING_BASE_POLICY_TYPE, "1.0.0"));
83     }
84
85     @Override
86     public String applicationName() {
87         return "monitoring";
88     }
89
90     @Override
91     public List<String> actionDecisionsSupported() {
92         return Arrays.asList("configure");
93     }
94
95     @Override
96     public synchronized List<ToscaPolicyTypeIdentifier> supportedPolicyTypes() {
97         return supportedPolicyTypes;
98     }
99
100     @Override
101     public boolean canSupportPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
102         //
103         // For Monitoring, we will attempt to support all versions
104         // of the policy type. Since we are only packaging a decision
105         // back with a JSON payload of the property contents.
106         //
107         return (policyTypeId.getName().equals(ONAP_MONITORING_BASE_POLICY_TYPE)
108                 || policyTypeId.getName().startsWith(ONAP_MONITORING_DERIVED_POLICY_TYPE));
109     }
110
111     @Override
112     public synchronized void loadPolicies(Map<String, Object> toscaPolicies) {
113         try {
114             //
115             // Convert the policies first
116             //
117             List<PolicyType> listPolicies = translator.scanAndConvertPolicies(toscaPolicies);
118             if (listPolicies.isEmpty()) {
119                 throw new ToscaPolicyConversionException("Converted 0 policies");
120             }
121             //
122             // Get our properties because we are going to update
123             //
124             Properties currentProperties = this.getProperties();
125             //
126             // Read in our Root Policy
127             //
128             Set<String> roots = XACMLProperties.getRootPolicyIDs(currentProperties);
129             if (roots.isEmpty()) {
130                 throw new ToscaPolicyConversionException("There are NO root policies defined");
131             }
132             //
133             // Really only should be one
134             //
135             String rootFile = currentProperties.getProperty(roots.iterator().next() + ".file");
136             try (InputStream is = new FileInputStream(rootFile)) {
137                 //
138                 // Read the Root Policy into memory
139                 //
140                 Object policyData = XACMLPolicyScanner.readPolicy(is);
141                 //
142                 // Should be a PolicySet
143                 //
144                 if (policyData instanceof PolicySetType) {
145                     //
146                     // Add the referenced policies into a new Root Policy
147                     //
148                     PolicyType[] newPolicies = listPolicies.toArray(new PolicyType[listPolicies.size()]);
149                     PolicySetType newRootPolicy = XacmlPolicyUtils.addPoliciesToXacmlRootPolicy(
150                             (PolicySetType) policyData, newPolicies);
151                     LOGGER.debug("New ROOT Policy");
152                     try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
153                         XACMLPolicyWriter.writePolicyFile(os, newRootPolicy);
154                         LOGGER.debug("{}", os);
155                     } catch (IOException e) {
156                         LOGGER.error("Failed to convert {}", e);
157                     }
158                     //
159                     // Save the new Policies to disk
160                     //
161                     for (PolicyType policy : newPolicies) {
162                         //
163                         // Construct the filename
164                         //
165                         Path refPath = XacmlPolicyUtils.constructUniquePolicyFilename(policy, this.getDataPath());
166                         //
167                         // Write the policy to disk
168                         // Maybe check for an error
169                         //
170                         XACMLPolicyWriter.writePolicyFile(refPath, policy);
171                         //
172                         // Save it off
173                         //
174                         XacmlPolicyUtils.addReferencedPolicy(currentProperties, refPath);
175                     }
176                     //
177                     // Save the root policy to disk
178                     //
179                     XACMLPolicyWriter.writePolicyFile(Paths.get(rootFile), newRootPolicy);
180                     //
181                     // Write the policies to disk
182                     //
183                     XacmlPolicyUtils.storeXacmlProperties(currentProperties,
184                             XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
185                     //
186                     // Reload the engine
187                     //
188                     this.createEngine(currentProperties);
189                 } else {
190                     throw new ToscaPolicyConversionException("Root policy isn't a PolicySet");
191                 }
192             }
193         } catch (IOException | ToscaPolicyConversionException e) {
194             LOGGER.error("Failed to loadPolicies {}", e);
195         }
196     }
197
198     @Override
199     public synchronized DecisionResponse makeDecision(DecisionRequest request) {
200         //
201         // Convert to a XacmlRequest
202         //
203         Request xacmlRequest = translator.convertRequest(request);
204         //
205         // Now get a decision
206         //
207         Response xacmlResponse = this.xacmlDecision(xacmlRequest);
208         //
209         // Convert to a DecisionResponse
210         //
211         return translator.convertResponse(xacmlResponse);
212     }
213
214 }