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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pdpx.main.rest;
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;
32 import java.util.ServiceLoader;
33 import java.util.stream.Collectors;
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;
46 public class XacmlPdpApplicationManager {
47 private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpApplicationManager.class);
51 private static XacmlPdpApplicationManager current;
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<>();
60 * One time to initialize the applications upon startup.
62 public XacmlPdpApplicationManager(XacmlApplicationParameters applicationParameters,
63 BusTopicParams policyApiParameters) {
64 if (LOGGER.isInfoEnabled()) {
65 LOGGER.info("Initialization applications {} {}", applicationParameters, policyApiParameters);
70 applicationLoader = ServiceLoader.load(XacmlApplicationServiceProvider.class);
72 // Iterate through the applications for actions and supported policy types
74 for (XacmlApplicationServiceProvider application : applicationLoader) {
75 if (LOGGER.isInfoEnabled()) {
76 LOGGER.info("Application {} supports {}", application.applicationName(),
77 application.supportedPolicyTypes());
80 // We are not going to make this available unless the application can
83 var applicationInitialized = false;
85 // Have it initialize at a path
88 initializeApplicationPath(Paths.get(applicationParameters.getApplicationPath()), application,
93 applicationInitialized = true;
94 } catch (XacmlApplicationException e) {
95 LOGGER.error("Failed to initialize path for {}", application.applicationName(), e);
97 if (applicationInitialized) {
99 // Iterate through the actions and save in the providerActionMap
101 for (String action : application.actionDecisionsSupported()) {
103 // Save the actions that it supports
105 providerActionMap.put(action, application);
108 // Add all the supported policy types
110 toscaPolicyTypeIdents.addAll(application.supportedPolicyTypes());
114 // we have initialized
116 LOGGER.info("Finished applications initialization {}", providerActionMap);
120 public XacmlApplicationServiceProvider findApplication(DecisionRequest request) {
121 return providerActionMap.get(request.getAction());
124 public XacmlApplicationServiceProvider findNativeApplication() {
125 return providerActionMap.get("native");
131 * @return the map containing ToscaPolicies
133 public Map<ToscaPolicy, XacmlApplicationServiceProvider> getToscaPolicies() {
134 return mapLoadedPolicies;
138 * getToscaPolicyIdentifiers.
140 * @return list of ToscaPolicyIdentifier
142 public List<ToscaConceptIdentifier> getToscaPolicyIdentifiers() {
144 // converting map to return List of ToscaPolicyIdentiers
146 return mapLoadedPolicies.keySet().stream().map(ToscaPolicy::getIdentifier).collect(Collectors.toList());
149 public List<ToscaConceptIdentifier> getToscaPolicyTypeIdents() {
150 return toscaPolicyTypeIdents;
154 * Finds the appropriate application and removes the policy.
156 * @param policy Incoming policy
158 public void removeUndeployedPolicy(ToscaPolicy policy) {
160 for (XacmlApplicationServiceProvider application : applicationLoader) {
162 if (application.unloadPolicy(policy)) {
163 if (LOGGER.isInfoEnabled()) {
164 LOGGER.info("Unloaded ToscaPolicy {} from application {}", policy.getMetadata(),
165 application.applicationName());
167 if (mapLoadedPolicies.remove(policy) == null) {
168 LOGGER.error("Failed to remove unloaded policy {} from map size {}", policy.getMetadata(),
169 mapLoadedPolicies.size());
172 } catch (XacmlApplicationException e) {
173 LOGGER.error("Failed to undeploy the Tosca Policy", e);
179 * Finds the appropriate application and loads the policy, throws an exception if it fails.
181 * @param policy Incoming policy
182 * @throws XacmlApplicationException if loadPolicy fails
184 public void loadDeployedPolicy(ToscaPolicy policy) throws XacmlApplicationException {
185 for (XacmlApplicationServiceProvider application : applicationLoader) {
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.
191 if (application.canSupportPolicyType(policy.getTypeIdentifier())) {
193 // Try to load the policy
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());
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.
210 throw new XacmlApplicationException("Application not found for policy type" + policy.getTypeIdentifier());
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.
218 * @return Total count added from all applications
220 public long getPolicyTypeCount() {
222 for (XacmlApplicationServiceProvider application : applicationLoader) {
223 types += application.supportedPolicyTypes().size();
229 * Gets the number of policies currently deployed.
231 * @return the number of policies currently deployed
233 public int getPolicyCount() {
234 return mapLoadedPolicies.size();
237 private void initializeApplicationPath(Path basePath, XacmlApplicationServiceProvider application,
238 BusTopicParams policyApiParameters) throws XacmlApplicationException {
240 // Making an assumption that all application names are unique, and
241 // they can result in a valid directory being created.
243 var path = Paths.get(basePath.toAbsolutePath().toString(), application.applicationName());
244 if (LOGGER.isInfoEnabled()) {
245 LOGGER.info("initializeApplicationPath {} at this path {}", application.applicationName(), path);
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.
253 if (! path.toFile().exists()) {
256 // Try to create the directory
258 Files.createDirectory(path);
259 } catch (IOException e) {
260 throw new XacmlApplicationException("Failed to create application directory " + path.toAbsolutePath(),
265 // Have the application initialize
267 application.initialize(path, policyApiParameters);