Integrate using Policy Type to find Matchable
[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     /**
122      * getToscaPolicies.
123      *
124      * @return the map containing ToscaPolicies
125      */
126     public Map<ToscaPolicy, XacmlApplicationServiceProvider> getToscaPolicies() {
127         return mapLoadedPolicies;
128     }
129
130     /**
131      * getToscaPolicyIdentifiers.
132      *
133      * @return list of ToscaPolicyIdentifier
134      */
135     public List<ToscaPolicyIdentifier> getToscaPolicyIdentifiers() {
136         //
137         // converting map to return List of ToscaPolicyIdentiers
138         //
139         return mapLoadedPolicies.keySet().stream().map(ToscaPolicy::getIdentifier).collect(Collectors.toList());
140     }
141
142     public List<ToscaPolicyTypeIdentifier> getToscaPolicyTypeIdents() {
143         return toscaPolicyTypeIdents;
144     }
145
146     /**
147      * Finds the appropriate application and removes the policy.
148      *
149      * @param policy Incoming policy
150      */
151     public void removeUndeployedPolicy(ToscaPolicy policy) {
152
153         for (XacmlApplicationServiceProvider application : applicationLoader) {
154             try {
155                 if (application.unloadPolicy(policy)) {
156                     if (LOGGER.isInfoEnabled()) {
157                         LOGGER.info("Unloaded ToscaPolicy {} from application {}", policy.getMetadata(),
158                             application.applicationName());
159                     }
160                     if (mapLoadedPolicies.remove(policy) == null) {
161                         LOGGER.error("Failed to remove unloaded policy {} from map size {}", policy.getMetadata(),
162                                 mapLoadedPolicies.size());
163                     }
164                 }
165             } catch (XacmlApplicationException e) {
166                 LOGGER.error("Failed to undeploy the Tosca Policy", e);
167             }
168         }
169     }
170
171     /**
172      * Finds the appropriate application and loads the policy.
173      *
174      * @param policy Incoming policy
175      */
176     public void loadDeployedPolicy(ToscaPolicy policy) {
177
178         for (XacmlApplicationServiceProvider application : applicationLoader) {
179             try {
180                 //
181                 // There should be only one application per policytype. We can
182                 // put more logic surrounding enforcement of that later. For now,
183                 // just use the first one found.
184                 //
185                 if (application.canSupportPolicyType(policy.getTypeIdentifier())) {
186                     if (application.loadPolicy(policy)) {
187                         if (LOGGER.isInfoEnabled()) {
188                             LOGGER.info("Loaded ToscaPolicy {} into application {}", policy.getMetadata(),
189                                 application.applicationName());
190                         }
191                         mapLoadedPolicies.put(policy, application);
192                     }
193                     return;
194                 }
195             } catch (XacmlApplicationException e) {
196                 LOGGER.error("Failed to load the Tosca Policy", e);
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 }