a5e1d030edd28a4c365e883b883274c80e229e62
[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 org.onap.policy.models.decisions.concepts.DecisionRequest;
33 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
34 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
35 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 public class XacmlPdpApplicationManager {
40     private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpApplicationManager.class);
41
42     private static boolean needsInit = true;
43     private static ServiceLoader<XacmlApplicationServiceProvider> applicationLoader;
44     private static Map<String, XacmlApplicationServiceProvider> providerActionMap = new HashMap<>();
45     private static List<ToscaPolicyTypeIdentifier> toscaPolicyTypeIdents = new ArrayList<>();
46
47     private XacmlPdpApplicationManager() {
48         super();
49     }
50
51     /**
52      * One time to initialize the applications upon startup.
53      */
54     public static void initializeApplications(Path applicationPath) {
55         //
56         // If we have already done this
57         //
58         if (! needsInit) {
59             LOGGER.error("Already initialized the applications");
60             return;
61         }
62         //
63         // Load service
64         //
65         applicationLoader = ServiceLoader.load(XacmlApplicationServiceProvider.class);
66         //
67         // Iterate through the applications for actions and supported policy types
68         //
69         for (XacmlApplicationServiceProvider application : applicationLoader) {
70             LOGGER.info("Application {} supports {}", application.applicationName(),
71                     application.supportedPolicyTypes());
72             //
73             // We are not going to make this available unless the application can
74             // install correctly.
75             //
76             boolean applicationInitialized = false;
77             //
78             // Have it initialize at a path
79             //
80             try {
81                 initializeApplicationPath(applicationPath, application);
82                 //
83                 // We are initialized
84                 //
85                 applicationInitialized = true;
86             } catch (XacmlApplicationException e) {
87                 LOGGER.error("Failed to initialize path for {}", application.applicationName(), e);
88             }
89             if (applicationInitialized) {
90                 //
91                 // Iterate through the actions and save in the providerActionMap
92                 //
93                 for (String action : application.actionDecisionsSupported()) {
94                     //
95                     // Save the actions that it supports
96                     //
97                     providerActionMap.put(action, application);
98                 }
99                 //
100                 // Add all the supported policy types
101                 //
102                 toscaPolicyTypeIdents.addAll(application.supportedPolicyTypes());
103             }
104         }
105         //
106         // we have initialized
107         //
108         needsInit = false;
109     }
110
111     public static XacmlApplicationServiceProvider findApplication(DecisionRequest request) {
112         return providerActionMap.get(request.getAction());
113     }
114
115     public static List<ToscaPolicyTypeIdentifier> getToscaPolicyTypeIdents() {
116         return toscaPolicyTypeIdents;
117     }
118
119     /**
120      * Returns the current count of policy types supported. This could be misleading a bit
121      * as some applications can support wildcard of policy types. Eg. onap.Monitoring.* as
122      * well as individual types/versions. Nevertheless useful for debugging and testing.
123      *
124      * @return Total count added from all applications
125      */
126     public static long getPolicyTypeCount() {
127         long types = 0;
128         for (XacmlApplicationServiceProvider application : applicationLoader) {
129             types += application.supportedPolicyTypes().size();
130         }
131         return types;
132     }
133
134     private static void initializeApplicationPath(Path basePath, XacmlApplicationServiceProvider application)
135             throws XacmlApplicationException {
136         //
137         // Making an assumption that all application names are unique, and
138         // they can result in a valid directory being created.
139         //
140         Path path = Paths.get(basePath.toAbsolutePath().toString(), application.applicationName());
141         LOGGER.info("initializeApplicationPath {} at this path {}", application.applicationName(), path);
142         //
143         // Create that the directory if it does not exist. Ideally
144         // this is only for testing, but could be used for production
145         // Probably better to have the docker container and/or helm
146         // scripts setup the local directory.
147         //
148         if (! path.toFile().exists()) {
149             try {
150                 //
151                 // Try to create the directory
152                 //
153                 Files.createDirectory(path);
154             } catch (IOException e) {
155                 LOGGER.error("Failed to create application directory", e);
156             }
157         }
158         //
159         // Have the application initialize
160         //
161         application.initialize(path);
162     }
163
164 }