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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.pdpx.main.rest;
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;
31 import java.util.ServiceLoader;
32 import java.util.stream.Collectors;
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;
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<ToscaPolicyTypeIdentifier> 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, RestServerParameters 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<ToscaPolicyIdentifier> getToscaPolicyIdentifiers() {
141 // converting map to return List of ToscaPolicyIdentiers
143 return mapLoadedPolicies.keySet().stream().map(ToscaPolicy::getIdentifier).collect(Collectors.toList());
146 public List<ToscaPolicyTypeIdentifier> 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 {
183 for (XacmlApplicationServiceProvider application : applicationLoader) {
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.
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());
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.
206 * @return Total count added from all applications
208 public long getPolicyTypeCount() {
210 for (XacmlApplicationServiceProvider application : applicationLoader) {
211 types += application.supportedPolicyTypes().size();
217 * Gets the number of policies currently deployed.
219 * @return the number of policies currently deployed
221 public int getPolicyCount() {
222 return mapLoadedPolicies.size();
225 private void initializeApplicationPath(Path basePath, XacmlApplicationServiceProvider application,
226 RestServerParameters policyApiParameters) throws XacmlApplicationException {
228 // Making an assumption that all application names are unique, and
229 // they can result in a valid directory being created.
231 Path path = Paths.get(basePath.toAbsolutePath().toString(), application.applicationName());
232 if (LOGGER.isInfoEnabled()) {
233 LOGGER.info("initializeApplicationPath {} at this path {}", application.applicationName(), path);
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.
241 if (! path.toFile().exists()) {
244 // Try to create the directory
246 Files.createDirectory(path);
247 } catch (IOException e) {
248 LOGGER.error("Failed to create application directory {}", path.toAbsolutePath().toString(), e);
252 // Have the application initialize
254 application.initialize(path, policyApiParameters);