Support of onap.policies.monitoring.tcagen2 2.0.0
[policy/xacml-pdp.git] / applications / monitoring / src / test / java / org / onap / policy / xacml / pdp / application / monitoring / MonitoringPdpApplicationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2021 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.xacml.pdp.application.monitoring;
25
26 import static org.assertj.core.api.Assertions.assertThat;
27
28 import com.att.research.xacml.api.Response;
29 import java.io.File;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Properties;
34 import java.util.ServiceLoader;
35 import org.apache.commons.lang3.tuple.Pair;
36 import org.junit.BeforeClass;
37 import org.junit.ClassRule;
38 import org.junit.FixMethodOrder;
39 import org.junit.Test;
40 import org.junit.rules.TemporaryFolder;
41 import org.junit.runners.MethodSorters;
42 import org.onap.policy.common.utils.coder.CoderException;
43 import org.onap.policy.common.utils.coder.StandardCoder;
44 import org.onap.policy.common.utils.resources.TextFileUtils;
45 import org.onap.policy.models.decisions.concepts.DecisionRequest;
46 import org.onap.policy.models.decisions.concepts.DecisionResponse;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
49 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
50 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
51 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
52 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
57 public class MonitoringPdpApplicationTest {
58
59     private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPdpApplicationTest.class);
60     private static final Properties properties = new Properties();
61     private static XacmlApplicationServiceProvider service;
62     private static DecisionRequest requestSinglePolicy;
63     private static DecisionRequest requestPolicyType;
64
65     private static final StandardCoder gson = new StandardCoder();
66
67     @ClassRule
68     public static final TemporaryFolder policyFolder = new TemporaryFolder();
69
70     /**
71      * Copies the xacml.properties and policies files into
72      * temporary folder and loads the service provider saving
73      * instance of provider off for other tests to use.
74      */
75     @BeforeClass
76     public static void setup() throws Exception {
77         //
78         // Load Single Decision Request
79         //
80         requestSinglePolicy = gson.decode(
81                 TextFileUtils
82                     .getTextFileAsString("../../main/src/test/resources/decisions/decision.single.input.json"),
83                     DecisionRequest.class);
84         // Load Single Decision Request
85         //
86         requestPolicyType = gson.decode(
87                 TextFileUtils
88                 .getTextFileAsString("../../main/src/test/resources/decisions/decision.policytype.input.json"),
89                 DecisionRequest.class);
90         //
91         // Setup our temporary folder
92         //
93         XacmlPolicyUtils.FileCreator myCreator = policyFolder::newFile;
94         File propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
95             properties, myCreator);
96         //
97         // Load XacmlApplicationServiceProvider service
98         //
99         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
100                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
101         //
102         // Look for our class instance and save it
103         //
104         StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
105         for (XacmlApplicationServiceProvider application : applicationLoader) {
106             //
107             // Is it our service?
108             //
109             if (application instanceof MonitoringPdpApplication) {
110                 //
111                 // Should be the first and only one
112                 //
113                 assertThat(service).isNull();
114                 service = application;
115             }
116             strDump.append(application.applicationName());
117             strDump.append(" supports ");
118             strDump.append(application.supportedPolicyTypes());
119             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
120         }
121         LOGGER.debug("{}", strDump);
122         //
123         // Tell it to initialize based on the properties file
124         // we just built for it.
125         //
126         service.initialize(propertiesFile.toPath().getParent(), null);
127     }
128
129     @Test
130     public void test1Basics() {
131         //
132         // Make sure there's an application name
133         //
134         assertThat(service.applicationName()).isNotEmpty();
135         //
136         // Ensure it has the supported policy types and
137         // can support the correct policy types.
138         //
139         assertThat(service.canSupportPolicyType(
140                 new ToscaConceptIdentifier("onap.policies.monitoring.tcagen2", "1.0.0"))).isTrue();
141         assertThat(service.canSupportPolicyType(
142             new ToscaConceptIdentifier("onap.policies.monitoring.tcagen2", "2.0.0"))).isTrue();
143         assertThat(service.canSupportPolicyType(
144                 new ToscaConceptIdentifier(
145                 "onap.policies.monitoring.foobar", "1.0.1"))).isTrue();
146         assertThat(service.canSupportPolicyType(
147             new ToscaConceptIdentifier(
148                 "onap.policies.monitoring.foobar", "2.0.1"))).isTrue();
149         assertThat(service.canSupportPolicyType(
150                 new ToscaConceptIdentifier("onap.foobar", "1.0.0"))).isFalse();
151         //
152         // Ensure it supports decisions
153         //
154         assertThat(service.actionDecisionsSupported()).contains("configure");
155     }
156
157     @Test
158     public void test2NoPolicies() {
159         //
160         // Ask for a decision
161         //
162         Pair<DecisionResponse, Response> decision = service.makeDecision(requestSinglePolicy, null);
163         LOGGER.info("Decision {}", decision);
164
165         assertThat(decision.getKey()).isNotNull();
166         assertThat(decision.getKey().getPolicies()).isEmpty();
167         //
168         // Test the branch for query params, and we have no policy anyway
169         //
170         Map<String, String[]> requestQueryParams = new HashMap<>();
171         decision = service.makeDecision(requestSinglePolicy, requestQueryParams);
172         LOGGER.info("Decision {}", decision);
173
174         assertThat(decision.getKey()).isNotNull();
175         assertThat(decision.getKey().getPolicies()).isEmpty();
176         //
177         // Test the branch for query params, and we have no policy anyway
178         //
179         requestQueryParams.put("abbrev", new String[] {"false"});
180         decision = service.makeDecision(requestSinglePolicy, requestQueryParams);
181         LOGGER.info("Decision {}", decision);
182
183         assertThat(decision.getKey()).isNotNull();
184         assertThat(decision.getKey().getPolicies()).isEmpty();
185         //
186         // Monitoring applications should not have this information returned
187         //
188         assertNoInfo(decision);
189     }
190
191     @Test
192     public void tes3AddvDnsPolicy() throws CoderException, XacmlApplicationException {
193         testAddPolicy("src/test/resources/vDNS.policy.input.yaml",
194             "onap.policies.monitoring.cdap.tca.hi.lo.app",
195             "onap.scaleout.tca");
196     }
197
198     @Test
199     public void tes4AddvFirewall1Policy() throws CoderException, XacmlApplicationException {
200         testAddPolicy("policies/vFirewall.policy.monitoring.input.tosca.yaml",
201             "onap.policies.monitoring.tcagen2",
202             "onap.vfirewall.tca");
203     }
204
205     @Test
206     public void tes5AddvFirewall2Policy() throws CoderException, XacmlApplicationException {
207         testAddPolicy("policies/vFirewall.policy.monitoring.input.tosca.v2.yaml",
208             "onap.policies.monitoring.tcagen2",
209             "onap.vfirewall.tca");
210     }
211
212     @SuppressWarnings("unchecked")
213     public void testAddPolicy(String policyResource, String policyType, String policyId)
214         throws CoderException, XacmlApplicationException {
215         //
216         // Now load the vDNS Policy - make sure
217         // the pdp can support it and have it load
218         // into the PDP.
219         //
220         //
221         // Now load the monitoring policies
222         //
223         final List<ToscaPolicy> loadedPolicies = TestUtils.loadPolicies(policyResource, service);
224
225         //
226         // Set the policy-id for the decision request.
227         //
228         requestSinglePolicy.getResource().put("policy-id", policyId);
229
230         //
231         // Ask for a decision
232         //
233         Pair<DecisionResponse, Response> decision = service.makeDecision(requestSinglePolicy, null);
234         LOGGER.info("Decision {}", decision);
235         //
236         // Should have one policy returned
237         //
238         assertThat(decision.getKey()).isNotNull();
239         assertThat(decision.getKey().getPolicies()).hasSize(1);
240         //
241         // Monitoring applications should not have this information returned
242         //
243         assertNoInfo(decision);
244         //
245         // Dump it out as Json
246         //
247         LOGGER.info(gson.encode(decision.getKey()));
248
249         //
250         // Set the policy-type for the decision request.
251         //
252         requestPolicyType.getResource().put("policy-type", policyType);
253
254         //
255         // Ask for a decision based on policy-type
256         //
257         decision = service.makeDecision(requestPolicyType, null);
258         LOGGER.info("Decision {}", decision);
259         //
260         // Should have one policy returned
261         //
262         assertThat(decision.getKey()).isNotNull();
263         assertThat(decision.getKey().getPolicies()).hasSize(1);
264         //
265         // Monitoring applications should not have this information returned
266         //
267         assertNoInfo(decision);
268         //
269         // Validate the full policy is returned
270         //
271         Map<String, Object> jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get(policyId);
272         assertThat(jsonPolicy).isNotNull();
273         assertThat(jsonPolicy.get("properties")).isNotNull();
274         //
275         // Dump it out as Json
276         //
277         LOGGER.info(gson.encode(decision.getKey()));
278         //
279         // Ask for abbreviated results
280         //
281         Map<String, String[]> requestQueryParams = new HashMap<>();
282         requestQueryParams.put("abbrev", new String[] {"true"});
283         decision = service.makeDecision(requestPolicyType, requestQueryParams);
284         LOGGER.info("Decision {}", decision);
285         //
286         // Should have one policy returned
287         //
288         assertThat(decision.getKey()).isNotNull();
289         assertThat(decision.getKey().getPolicies()).hasSize(1);
290         //
291         // Monitoring applications should not have this information returned
292         //
293         assertNoInfo(decision);
294         //
295         // Validate an abbreviated policy is returned
296         //
297         jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get(policyId);
298         assertThat(jsonPolicy).isNotNull().doesNotContainKey("properties");
299         //
300         // Don't Ask for abbreviated results
301         //
302         requestQueryParams = new HashMap<>();
303         requestQueryParams.put("abbrev", new String[] {"false"});
304         decision = service.makeDecision(requestPolicyType, requestQueryParams);
305         LOGGER.info("Decision {}", decision);
306         //
307         // Should have one policy returned
308         //
309         assertThat(decision.getKey()).isNotNull();
310         assertThat(decision.getKey().getPolicies()).hasSize(1);
311         //
312         // Monitoring applications should not have this information returned
313         //
314         assertNoInfo(decision);
315         //
316         // And should have full policy returned
317         //
318         jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get(policyId);
319         assertThat(jsonPolicy).isNotNull();
320         assertThat(jsonPolicy.get("properties")).isNotNull();
321         //
322         // Throw an unknown exception
323         //
324         requestQueryParams = new HashMap<>();
325         requestQueryParams.put("unknown", new String[] {"true"});
326         decision = service.makeDecision(requestPolicyType, requestQueryParams);
327         LOGGER.info("Decision {}", decision);
328
329         assertThat(decision.getKey()).isNotNull();
330         assertThat(decision.getKey().getPolicies()).hasSize(1);
331         jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get(policyId);
332         assertThat(jsonPolicy).isNotNull();
333         assertThat(jsonPolicy.get("properties")).isNotNull();
334         //
335         // Dump it out as Json
336         //
337         LOGGER.info(gson.encode(decision.getKey()));
338         //
339         // Now unload it
340         //
341         LOGGER.info("Now testing unloading of policy");
342         for (ToscaPolicy policy : loadedPolicies) {
343             assertThat(service.unloadPolicy(policy)).isTrue();
344         }
345         //
346         // Ask for a decision
347         //
348         decision = service.makeDecision(requestSinglePolicy, null);
349         LOGGER.info("Decision {}", decision.getKey());
350
351         assertThat(decision.getKey()).isNotNull();
352         assertThat(decision.getKey().getPolicies()).isEmpty();
353     }
354
355     private void assertNoInfo(Pair<DecisionResponse, Response> decision) {
356         assertThat(decision.getKey().getAdvice()).isNull();
357         assertThat(decision.getKey().getObligations()).isNull();
358         assertThat(decision.getKey().getAttributes()).isNull();
359     }
360
361 }