Build XACML PDP support for native xacml policy type
[policy/xacml-pdp.git] / main / src / main / java / org / onap / policy / pdpx / main / rest / XacmlPdpApplicationManager.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pdpx.main.rest;
22
23 import java.io.IOException;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26 import java.nio.file.Paths;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.ServiceLoader;
32 import java.util.stream.Collectors;
33 import lombok.Getter;
34 import lombok.Setter;
35 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
36 import org.onap.policy.models.decisions.concepts.DecisionRequest;
37 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
38 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
39 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
40 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
41 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 public class XacmlPdpApplicationManager {
46     private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpApplicationManager.class);
47
48     @Getter
49     @Setter
50     private static XacmlPdpApplicationManager current;
51
52     private ServiceLoader<XacmlApplicationServiceProvider> applicationLoader;
53     private Map<String, XacmlApplicationServiceProvider> providerActionMap = new HashMap<>();
54     private List<ToscaPolicyTypeIdentifier> toscaPolicyTypeIdents = new ArrayList<>();
55     private Map<ToscaPolicy, XacmlApplicationServiceProvider> mapLoadedPolicies = new HashMap<>();
56
57
58     /**
59      * One time to initialize the applications upon startup.
60      */
61     public XacmlPdpApplicationManager(Path applicationPath, RestServerParameters policyApiParameters) {
62         if (LOGGER.isInfoEnabled()) {
63             LOGGER.info("Initialization applications {} {}", applicationPath.toAbsolutePath(), policyApiParameters);
64         }
65         //
66         // Load service
67         //
68         applicationLoader = ServiceLoader.load(XacmlApplicationServiceProvider.class);
69         //
70         // Iterate through the applications for actions and supported policy types
71         //
72         for (XacmlApplicationServiceProvider application : applicationLoader) {
73             if (LOGGER.isInfoEnabled()) {
74                 LOGGER.info("Application {} supports {}", application.applicationName(),
75                     application.supportedPolicyTypes());
76             }
77             //
78             // We are not going to make this available unless the application can
79             // install correctly.
80             //
81             boolean applicationInitialized = false;
82             //
83             // Have it initialize at a path
84             //
85             try {
86                 initializeApplicationPath(applicationPath, application, policyApiParameters);
87                 //
88                 // We are initialized
89                 //
90                 applicationInitialized = true;
91             } catch (XacmlApplicationException e) {
92                 LOGGER.error("Failed to initialize path for {}", application.applicationName(), e);
93             }
94             if (applicationInitialized) {
95                 //
96                 // Iterate through the actions and save in the providerActionMap
97                 //
98                 for (String action : application.actionDecisionsSupported()) {
99                     //
100                     // Save the actions that it supports
101                     //
102                     providerActionMap.put(action, application);
103                 }
104                 //
105                 // Add all the supported policy types
106                 //
107                 toscaPolicyTypeIdents.addAll(application.supportedPolicyTypes());
108             }
109         }
110         //
111         // we have initialized
112         //
113         LOGGER.info("Finished applications initialization {}", providerActionMap);
114
115     }
116
117     public XacmlApplicationServiceProvider findApplication(DecisionRequest request) {
118         return providerActionMap.get(request.getAction());
119     }
120
121     public XacmlApplicationServiceProvider findNativeApplication() {
122         return providerActionMap.get("native");
123     }
124
125     /**
126      * getToscaPolicies.
127      *
128      * @return the map containing ToscaPolicies
129      */
130     public Map<ToscaPolicy, XacmlApplicationServiceProvider> getToscaPolicies() {
131         return mapLoadedPolicies;
132     }
133
134     /**
135      * getToscaPolicyIdentifiers.
136      *
137      * @return list of ToscaPolicyIdentifier
138      */
139     public List<ToscaPolicyIdentifier> getToscaPolicyIdentifiers() {
140         //
141         // converting map to return List of ToscaPolicyIdentiers
142         //
143         return mapLoadedPolicies.keySet().stream().map(ToscaPolicy::getIdentifier).collect(Collectors.toList());
144     }
145
146     public List<ToscaPolicyTypeIdentifier> getToscaPolicyTypeIdents() {
147         return toscaPolicyTypeIdents;
148     }
149
150     /**
151      * Finds the appropriate application and removes the policy.
152      *
153      * @param policy Incoming policy
154      */
155     public void removeUndeployedPolicy(ToscaPolicy policy) {
156
157         for (XacmlApplicationServiceProvider application : applicationLoader) {
158             try {
159                 if (application.unloadPolicy(policy)) {
160                     if (LOGGER.isInfoEnabled()) {
161                         LOGGER.info("Unloaded ToscaPolicy {} from application {}", policy.getMetadata(),
162                             application.applicationName());
163                     }
164                     if (mapLoadedPolicies.remove(policy) == null) {
165                         LOGGER.error("Failed to remove unloaded policy {} from map size {}", policy.getMetadata(),
166                                 mapLoadedPolicies.size());
167                     }
168                 }
169             } catch (XacmlApplicationException e) {
170                 LOGGER.error("Failed to undeploy the Tosca Policy", e);
171             }
172         }
173     }
174
175     /**
176      * Finds the appropriate application and loads the policy, throws an exception if it fails.
177      *
178      * @param policy Incoming policy
179      * @throws XacmlApplicationException if loadPolicy fails
180      */
181     public void loadDeployedPolicy(ToscaPolicy policy) throws XacmlApplicationException {
182
183         for (XacmlApplicationServiceProvider application : applicationLoader) {
184             //
185             // There should be only one application per policytype. We can
186             // put more logic surrounding enforcement of that later. For now,
187             // just use the first one found.
188             //
189             if (application.canSupportPolicyType(policy.getTypeIdentifier())) {
190                 application.loadPolicy(policy);
191                 mapLoadedPolicies.put(policy, application);
192                 if (LOGGER.isInfoEnabled()) {
193                     LOGGER.info("Loaded ToscaPolicy {} into application {}", policy.getMetadata(),
194                             application.applicationName());
195                 }
196                 return;
197             }
198         }
199     }
200
201     /**
202      * Returns the current count of policy types supported. This could be misleading a bit
203      * as some applications can support wildcard of policy types. Eg. onap.Monitoring.* as
204      * well as individual types/versions. Nevertheless useful for debugging and testing.
205      *
206      * @return Total count added from all applications
207      */
208     public long getPolicyTypeCount() {
209         long types = 0;
210         for (XacmlApplicationServiceProvider application : applicationLoader) {
211             types += application.supportedPolicyTypes().size();
212         }
213         return types;
214     }
215
216     /**
217      * Gets the number of policies currently deployed.
218      *
219      * @return the number of policies currently deployed
220      */
221     public int getPolicyCount() {
222         return mapLoadedPolicies.size();
223     }
224
225     private void initializeApplicationPath(Path basePath, XacmlApplicationServiceProvider application,
226             RestServerParameters policyApiParameters) throws XacmlApplicationException {
227         //
228         // Making an assumption that all application names are unique, and
229         // they can result in a valid directory being created.
230         //
231         Path path = Paths.get(basePath.toAbsolutePath().toString(), application.applicationName());
232         if (LOGGER.isInfoEnabled()) {
233             LOGGER.info("initializeApplicationPath {} at this path {}", application.applicationName(), path);
234         }
235         //
236         // Create that the directory if it does not exist. Ideally
237         // this is only for testing, but could be used for production
238         // Probably better to have the docker container and/or helm
239         // scripts setup the local directory.
240         //
241         if (! path.toFile().exists()) {
242             try {
243                 //
244                 // Try to create the directory
245                 //
246                 Files.createDirectory(path);
247             } catch (IOException e) {
248                 LOGGER.error("Failed to create application directory {}", path.toAbsolutePath().toString(), e);
249             }
250         }
251         //
252         // Have the application initialize
253         //
254         application.initialize(path, policyApiParameters);
255     }
256 }