Fix optimization supported types
[policy/xacml-pdp.git] / applications / optimization / src / main / java / org / onap / policy / xacml / pdp / application / optimization / OptimizationPdpApplication.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.xacml.pdp.application.optimization;
24
25 import com.att.research.xacml.api.Advice;
26 import com.att.research.xacml.api.AttributeAssignment;
27 import com.att.research.xacml.api.Decision;
28 import com.att.research.xacml.api.Response;
29 import com.att.research.xacml.api.Result;
30 import java.nio.file.Path;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.List;
36 import java.util.Map;
37 import org.apache.commons.lang3.tuple.Pair;
38 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
39 import org.onap.policy.models.decisions.concepts.DecisionRequest;
40 import org.onap.policy.models.decisions.concepts.DecisionResponse;
41 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
42 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
43 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
44 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
45 import org.onap.policy.pdp.xacml.application.common.std.StdXacmlApplicationServiceProvider;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class OptimizationPdpApplication extends StdXacmlApplicationServiceProvider {
50
51     private static final Logger LOGGER = LoggerFactory.getLogger(OptimizationPdpApplication.class);
52     private static final String STRING_VERSION100 = "1.0.0";
53     private static final String RESOURCE_SUBSCRIBERNAME = "subscriberName";
54     private static final String RESOURCE_POLICYTYPE = "policy-type";
55     private static final String RESOURCE_SCOPE = "scope";
56
57     public static final String POLICYTYPE_AFFINITY = "onap.policies.optimization.resource.AffinityPolicy";
58     public static final String POLICYTYPE_SUBSCRIBER = "onap.policies.optimization.service.SubscriberPolicy";
59     public static final String POLICYTYPE_DISTANCE = "onap.policies.optimization.resource.DistancePolicy";
60     public static final String POLICYTYPE_HPA = "onap.policies.optimization.resource.HpaPolicy";
61     public static final String POLICYTYPE_OPTIMIZATION = "onap.policies.optimization.resource.OptimizationPolicy";
62     public static final String POLICYTYPE_PCI = "onap.policies.optimization.resource.PciPolicy";
63     public static final String POLICYTYPE_QUERY = "onap.policies.optimization.service.QueryPolicy";
64     public static final String POLICYTYPE_VIMFIT = "onap.policies.optimization.resource.Vim_fit";
65     public static final String POLICYTYPE_VNF = "onap.policies.optimization.resource.VnfPolicy";
66     public static final String ONAP_OPTIMIZATION_DERIVED_POLICY_TYPE = "onap.policies.optimization.";
67
68     private OptimizationPdpApplicationTranslator translator = new OptimizationPdpApplicationTranslator();
69     private List<ToscaPolicyTypeIdentifier> supportedPolicyTypes = new ArrayList<>();
70
71     /**
72      * Constructor.
73      */
74     public OptimizationPdpApplication() {
75         this.supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(POLICYTYPE_AFFINITY, STRING_VERSION100));
76         this.supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(POLICYTYPE_DISTANCE, STRING_VERSION100));
77         this.supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(POLICYTYPE_HPA, STRING_VERSION100));
78         this.supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(POLICYTYPE_OPTIMIZATION, STRING_VERSION100));
79         this.supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(POLICYTYPE_PCI, STRING_VERSION100));
80         this.supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(POLICYTYPE_QUERY, STRING_VERSION100));
81         this.supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(POLICYTYPE_SUBSCRIBER, STRING_VERSION100));
82         this.supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(POLICYTYPE_VIMFIT, STRING_VERSION100));
83         this.supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(POLICYTYPE_VNF, STRING_VERSION100));
84     }
85
86     @Override
87     public String applicationName() {
88         return "optimization";
89     }
90
91     @Override
92     public List<String> actionDecisionsSupported() {
93         return Arrays.asList("optimize");
94     }
95
96     @Override
97     public void initialize(Path pathForData, RestServerParameters policyApiParameters)
98             throws XacmlApplicationException {
99         //
100         // Store our API parameters and path for translator so it
101         // can go get Policy Types
102         //
103         this.translator.setPathForData(pathForData);
104         this.translator.setApiRestParameters(policyApiParameters);
105         //
106         // Let our super class do its thing
107         //
108         super.initialize(pathForData, policyApiParameters);
109     }
110
111     @Override
112     public synchronized List<ToscaPolicyTypeIdentifier> supportedPolicyTypes() {
113         return Collections.unmodifiableList(supportedPolicyTypes);
114     }
115
116     @Override
117     public boolean canSupportPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
118         //
119         // For the time being, restrict this if the version isn't known.
120         // Could be too difficult to support changing of versions dynamically.
121         //
122         for (ToscaPolicyTypeIdentifier supported : this.supportedPolicyTypes) {
123             if (policyTypeId.equals(supported)) {
124                 LOGGER.info("optimization can support {}", supported);
125                 return true;
126             }
127         }
128         //
129         // Support derived types
130         //
131         return policyTypeId.getName().startsWith(ONAP_OPTIMIZATION_DERIVED_POLICY_TYPE);
132     }
133
134     @Override
135     public Pair<DecisionResponse, Response> makeDecision(DecisionRequest request,
136             Map<String, String[]> requestQueryParams) {
137         //
138         // In case we have a subcriber policy
139         //
140         Response xacmlSubscriberResponse = null;
141         //
142         // Check if there are subject attributes for subscriber
143         //
144         if (hasSubscriberAttributes(request)) {
145             //
146             // We must do an initial request to pull subscriber attributes
147             //
148             LOGGER.info("Request Subscriber attributes");
149             //
150             // Convert the request
151             //
152             DecisionRequest subscriberRequest = new DecisionRequest(request);
153             //
154             // Override the PolicyType to ensure we are only looking at Subscriber Policies
155             //
156             if (subscriberRequest.getResource().containsKey(RESOURCE_POLICYTYPE)) {
157                 subscriberRequest.getResource().remove(RESOURCE_POLICYTYPE);
158             }
159             subscriberRequest.getResource().put(RESOURCE_POLICYTYPE, POLICYTYPE_SUBSCRIBER);
160             //
161             // Convert to a XacmlRequest and get a decision
162             //
163             try {
164                 xacmlSubscriberResponse =
165                         this.xacmlDecision(OptimizationSubscriberRequest.createInstance(subscriberRequest));
166             } catch (XacmlApplicationException e) {
167                 LOGGER.error("Could not create subscriberName request", e);
168             }
169             //
170             // Check the response for subscriber attributes and add them
171             // to the initial request.
172             //
173             if (xacmlSubscriberResponse != null && ! addSubscriberAttributes(xacmlSubscriberResponse, request)) {
174                 LOGGER.error("Failed to get subscriber role attributes");
175                 //
176                 // Convert to a DecisionResponse
177                 //
178                 return Pair.of(this.getTranslator().convertResponse(xacmlSubscriberResponse), xacmlSubscriberResponse);
179             }
180         }
181         //
182         // Make the decision
183         //
184         Pair<DecisionResponse, Response> decisionPair = super.makeDecision(request, requestQueryParams);
185         //
186         // Add back in advice from subscriber
187         //
188         if (xacmlSubscriberResponse != null) {
189             addSubscriberAdvice(xacmlSubscriberResponse, decisionPair.getLeft());
190         }
191         return decisionPair;
192     }
193
194     @Override
195     protected ToscaPolicyTranslator getTranslator(String type) {
196         //
197         // Return translator
198         //
199         return translator;
200     }
201
202     @SuppressWarnings("unchecked")
203     private boolean hasSubscriberAttributes(DecisionRequest request) {
204         return request.getContext() != null
205                 && request.getContext().containsKey(RESOURCE_SUBSCRIBERNAME)
206                 && request.getContext().get(RESOURCE_SUBSCRIBERNAME) instanceof List
207                 && ! ((List<String>) request.getContext().get(RESOURCE_SUBSCRIBERNAME)).isEmpty();
208     }
209
210     private boolean addSubscriberAttributes(Response xacmlResponse, DecisionRequest initialRequest) {
211         //
212         // This has multiple results right now because of how the attributes were added to the
213         // request. That will have to be fixed in the future, for now find the Permit result
214         // and add the role attributes as they will be used in the next request.
215         //
216         for (Result result : xacmlResponse.getResults()) {
217             //
218             // Check the result
219             //
220             if (result.getStatus().isOk() && result.getDecision().equals(Decision.PERMIT)) {
221                 //
222                 // Pull out the advice which has attributes
223                 //
224                 scanAdvice(result.getAssociatedAdvice(), initialRequest);
225                 //
226                 // PLD this is an assumption that all is good
227                 //
228                 return true;
229             } else {
230                 LOGGER.error("XACML result not ok {} or Permit {}", result.getStatus(), result.getDecision());
231             }
232         }
233         return false;
234     }
235
236     private void addSubscriberAdvice(Response xacmlResponse, DecisionResponse response) {
237         //
238         // Again find the Permit result
239         //
240         for (Result result : xacmlResponse.getResults()) {
241             //
242             // Check the result
243             //
244             if (result.getStatus().isOk() && Decision.PERMIT.equals(result.getDecision())) {
245                 this.translator.scanAdvice(result.getAssociatedAdvice(), response);
246             }
247         }
248     }
249
250
251     @SuppressWarnings("unchecked")
252     private void scanAdvice(Collection<Advice> adviceCollection, DecisionRequest initialRequest) {
253         //
254         // There really should only be one advice object
255         //
256         for (Advice advice : adviceCollection) {
257             //
258             // Look for the optimization specific advice
259             //
260             if (! ToscaDictionary.ID_ADVICE_OPTIMIZATION_SUBSCRIBER.equals(advice.getId())) {
261                 LOGGER.error("Unsupported advice id {}", advice.getId());
262                 continue;
263             }
264             //
265             // Get the attributes and add them
266             //
267             for (AttributeAssignment attribute : advice.getAttributeAssignments()) {
268                 //
269                 // If this is subscriber role
270                 //
271                 if (ToscaDictionary.ID_ADVICE_OPTIMIZATION_SUBSCRIBER_ROLE.equals(attribute.getAttributeId())) {
272                     ((List<String>) initialRequest.getResource().get(RESOURCE_SCOPE))
273                             .add(attribute.getAttributeValue().getValue().toString());
274                 }
275             }
276         }
277     }
278
279 }