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.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
45 public class XacmlPdpApplicationManager {
46 private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpApplicationManager.class);
50 private static XacmlPdpApplicationManager current;
52 private ServiceLoader<XacmlApplicationServiceProvider> applicationLoader;
53 private Map<String, XacmlApplicationServiceProvider> providerActionMap = new HashMap<>();
54 private List<ToscaConceptIdentifier> toscaPolicyTypeIdents = new ArrayList<>();
55 private Map<ToscaPolicy, XacmlApplicationServiceProvider> mapLoadedPolicies = new HashMap<>();
59 * One time to initialize the applications upon startup.
61 public XacmlPdpApplicationManager(Path applicationPath, BusTopicParams policyApiParameters) {
62 if (LOGGER.isInfoEnabled()) {
63 LOGGER.info("Initialization applications {} {}", applicationPath.toAbsolutePath(), policyApiParameters);
68 applicationLoader = ServiceLoader.load(XacmlApplicationServiceProvider.class);
70 // Iterate through the applications for actions and supported policy types
72 for (XacmlApplicationServiceProvider application : applicationLoader) {
73 if (LOGGER.isInfoEnabled()) {
74 LOGGER.info("Application {} supports {}", application.applicationName(),
75 application.supportedPolicyTypes());
78 // We are not going to make this available unless the application can
81 boolean applicationInitialized = false;
83 // Have it initialize at a path
86 initializeApplicationPath(applicationPath, application, policyApiParameters);
90 applicationInitialized = true;
91 } catch (XacmlApplicationException e) {
92 LOGGER.error("Failed to initialize path for {}", application.applicationName(), e);
94 if (applicationInitialized) {
96 // Iterate through the actions and save in the providerActionMap
98 for (String action : application.actionDecisionsSupported()) {
100 // Save the actions that it supports
102 providerActionMap.put(action, application);
105 // Add all the supported policy types
107 toscaPolicyTypeIdents.addAll(application.supportedPolicyTypes());
111 // we have initialized
113 LOGGER.info("Finished applications initialization {}", providerActionMap);
117 public XacmlApplicationServiceProvider findApplication(DecisionRequest request) {
118 return providerActionMap.get(request.getAction());
121 public XacmlApplicationServiceProvider findNativeApplication() {
122 return providerActionMap.get("native");
128 * @return the map containing ToscaPolicies
130 public Map<ToscaPolicy, XacmlApplicationServiceProvider> getToscaPolicies() {
131 return mapLoadedPolicies;
135 * getToscaPolicyIdentifiers.
137 * @return list of ToscaPolicyIdentifier
139 public List<ToscaConceptIdentifier> getToscaPolicyIdentifiers() {
141 // converting map to return List of ToscaPolicyIdentiers
143 return mapLoadedPolicies.keySet().stream().map(ToscaPolicy::getIdentifier).collect(Collectors.toList());
146 public List<ToscaConceptIdentifier> getToscaPolicyTypeIdents() {
147 return toscaPolicyTypeIdents;
151 * Finds the appropriate application and removes the policy.
153 * @param policy Incoming policy
155 public void removeUndeployedPolicy(ToscaPolicy policy) {
157 for (XacmlApplicationServiceProvider application : applicationLoader) {
159 if (application.unloadPolicy(policy)) {
160 if (LOGGER.isInfoEnabled()) {
161 LOGGER.info("Unloaded ToscaPolicy {} from application {}", policy.getMetadata(),
162 application.applicationName());
164 if (mapLoadedPolicies.remove(policy) == null) {
165 LOGGER.error("Failed to remove unloaded policy {} from map size {}", policy.getMetadata(),
166 mapLoadedPolicies.size());
169 } catch (XacmlApplicationException e) {
170 LOGGER.error("Failed to undeploy the Tosca Policy", e);
176 * Finds the appropriate application and loads the policy, throws an exception if it fails.
178 * @param policy Incoming policy
179 * @throws XacmlApplicationException if loadPolicy fails
181 public void loadDeployedPolicy(ToscaPolicy policy) throws XacmlApplicationException {
182 for (XacmlApplicationServiceProvider application : applicationLoader) {
184 // There should be only one application per policytype. We can
185 // put more logic surrounding enforcement of that later. For now,
186 // just use the first one found.
188 if (application.canSupportPolicyType(policy.getTypeIdentifier())) {
190 // Try to load the policy
192 application.loadPolicy(policy);
193 mapLoadedPolicies.put(policy, application);
194 if (LOGGER.isInfoEnabled()) {
195 LOGGER.info("Loaded ToscaPolicy {} into application {}", policy.getMetadata(),
196 application.applicationName());
202 // Ideally we shouldn't ever get here if we
203 // are ensuring we are reporting a set of Policy Types and the
204 // pap honors that. The loadPolicy for each application should be
205 // the one throwing exceptions if there are any errors in the policy type.
207 throw new XacmlApplicationException("Application not found for policy type" + policy.getTypeIdentifier());
211 * Returns the current count of policy types supported. This could be misleading a bit
212 * as some applications can support wildcard of policy types. Eg. onap.Monitoring.* as
213 * well as individual types/versions. Nevertheless useful for debugging and testing.
215 * @return Total count added from all applications
217 public long getPolicyTypeCount() {
219 for (XacmlApplicationServiceProvider application : applicationLoader) {
220 types += application.supportedPolicyTypes().size();
226 * Gets the number of policies currently deployed.
228 * @return the number of policies currently deployed
230 public int getPolicyCount() {
231 return mapLoadedPolicies.size();
234 private void initializeApplicationPath(Path basePath, XacmlApplicationServiceProvider application,
235 BusTopicParams policyApiParameters) throws XacmlApplicationException {
237 // Making an assumption that all application names are unique, and
238 // they can result in a valid directory being created.
240 Path path = Paths.get(basePath.toAbsolutePath().toString(), application.applicationName());
241 if (LOGGER.isInfoEnabled()) {
242 LOGGER.info("initializeApplicationPath {} at this path {}", application.applicationName(), path);
245 // Create that the directory if it does not exist. Ideally
246 // this is only for testing, but could be used for production
247 // Probably better to have the docker container and/or helm
248 // scripts setup the local directory.
250 if (! path.toFile().exists()) {
253 // Try to create the directory
255 Files.createDirectory(path);
256 } catch (IOException e) {
257 throw new XacmlApplicationException("Failed to create application directory " + path.toAbsolutePath(),
262 // Have the application initialize
264 application.initialize(path, policyApiParameters);