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