af6e654895dc9c281fbdf19441e04e784f3c8a44
[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 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.monitoring;
24
25 import static org.assertj.core.api.Assertions.assertThat;
26 import static org.assertj.core.api.Assertions.assertThatCode;
27 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
28
29 import com.att.research.xacml.util.XACMLProperties;
30 import com.google.common.io.Files;
31 import com.google.gson.Gson;
32
33 import java.io.File;
34 import java.io.FileInputStream;
35 import java.io.FileOutputStream;
36 import java.io.InputStream;
37 import java.io.OutputStream;
38 import java.nio.file.Path;
39 import java.nio.file.Paths;
40 import java.util.Iterator;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.Map.Entry;
44 import java.util.Properties;
45 import java.util.ServiceLoader;
46
47 import org.junit.BeforeClass;
48 import org.junit.ClassRule;
49 import org.junit.Test;
50 import org.junit.rules.TemporaryFolder;
51 import org.onap.policy.common.utils.resources.TextFileUtils;
52 import org.onap.policy.models.decisions.concepts.DecisionRequest;
53 import org.onap.policy.models.decisions.concepts.DecisionResponse;
54 import org.onap.policy.models.decisions.serialization.DecisionRequestMessageBodyHandler;
55 import org.onap.policy.models.decisions.serialization.DecisionResponseMessageBodyHandler;
56 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
57 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60 import org.yaml.snakeyaml.Yaml;
61
62 public class MonitoringPdpApplicationTest {
63
64     private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPdpApplicationTest.class);
65     private static Properties properties = new Properties();
66     private static File propertiesFile;
67     private static XacmlApplicationServiceProvider service;
68     private static DecisionRequest requestSinglePolicy;
69
70     private static Gson gsonDecisionRequest;
71     private static Gson gsonDecisionResponse;
72
73     @ClassRule
74     public static final TemporaryFolder policyFolder = new TemporaryFolder();
75
76     /**
77      * Load a test engine.
78      */
79     @BeforeClass
80     public static void setup() {
81         assertThatCode(() -> {
82             //
83             // Create our Gson builder
84             //
85             gsonDecisionRequest = new DecisionRequestMessageBodyHandler().getGson();
86             gsonDecisionResponse = new DecisionResponseMessageBodyHandler().getGson();
87             //
88             // Load Single Decision Request
89             //
90             requestSinglePolicy = gsonDecisionRequest.fromJson(
91                     TextFileUtils
92                         .getTextFileAsString("../../main/src/test/resources/decisions/decision.single.input.json"),
93                         DecisionRequest.class);
94             //
95             // Copy all the properties and root policies to the temporary folder
96             //
97             try (InputStream is = new FileInputStream("src/test/resources/xacml.properties")) {
98                 //
99                 // Load it in
100                 //
101                 properties.load(is);
102                 propertiesFile = policyFolder.newFile("xacml.properties");
103                 //
104                 // Copy the root policies
105                 //
106                 for (String root : XACMLProperties.getRootPolicyIDs(properties)) {
107                     //
108                     // Get a file
109                     //
110                     Path rootPath = Paths.get(properties.getProperty(root + ".file"));
111                     LOGGER.debug("Root file {} {}", rootPath, rootPath.getFileName());
112                     //
113                     // Construct new file name
114                     //
115                     File newRootPath = policyFolder.newFile(rootPath.getFileName().toString());
116                     //
117                     // Copy it
118                     //
119                     Files.copy(rootPath.toFile(), newRootPath);
120                     assertThat(newRootPath).exists();
121                     //
122                     // Point to where the new policy is in the temp dir
123                     //
124                     properties.setProperty(root + ".file", newRootPath.getAbsolutePath());
125                 }
126                 try (OutputStream os = new FileOutputStream(propertiesFile.getAbsolutePath())) {
127                     properties.store(os, "");
128                     assertThat(propertiesFile).exists();
129                 }
130             }
131             //
132             // Load service
133             //
134             ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
135                     ServiceLoader.load(XacmlApplicationServiceProvider.class);
136             //
137             // Iterate through them - I could store the object as
138             // XacmlApplicationServiceProvider pointer.
139             //
140             // Try this later.
141             //
142             StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
143             Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
144             while (iterator.hasNext()) {
145                 XacmlApplicationServiceProvider application = iterator.next();
146                 //
147                 // Is it our service?
148                 //
149                 if (application instanceof MonitoringPdpApplication) {
150                     //
151                     // Should be the first and only one
152                     //
153                     assertThat(service).isNull();
154                     service = application;
155                 }
156                 strDump.append(application.applicationName());
157                 strDump.append(" supports ");
158                 strDump.append(application.supportedPolicyTypes());
159                 strDump.append(System.lineSeparator());
160             }
161             LOGGER.debug("{}", strDump);
162             //
163             // Tell it to initialize based on the properties file
164             // we just built for it.
165             //
166             service.initialize(propertiesFile.toPath().getParent());
167             //
168             // Make sure there's an application name
169             //
170             assertThat(service.applicationName()).isNotEmpty();
171             //
172             // Ensure it has the supported policy types and
173             // can support the correct policy types.
174             //
175             assertThat(service.canSupportPolicyType("onap.Monitoring", "1.0.0")).isTrue();
176             assertThat(service.canSupportPolicyType("onap.Monitoring", "1.5.0")).isTrue();
177             assertThat(service.canSupportPolicyType("onap.policies.monitoring.foobar", "1.0.1")).isTrue();
178             assertThat(service.canSupportPolicyType("onap.foobar", "1.0.0")).isFalse();
179             assertThat(service.supportedPolicyTypes()).contains("onap.Monitoring");
180             //
181             // Ensure it supports decisions
182             //
183             assertThat(service.actionDecisionsSupported()).contains("configure");
184         }).doesNotThrowAnyException();
185     }
186
187     @Test
188     public void testNoPolicies() {
189         //
190         // Make a simple decision - NO policies are loaded
191         //
192         assertThatCode(() -> {
193             //
194             // Ask for a decision
195             //
196             DecisionResponse response = service.makeDecision(requestSinglePolicy);
197             LOGGER.info("Decision {}", response);
198
199             assertThat(response).isNotNull();
200             assertThat(response.getErrorMessage()).isNullOrEmpty();
201             assertThat(response.getPolicies().size()).isEqualTo(0);
202
203         }).doesNotThrowAnyException();
204     }
205
206     @SuppressWarnings("unchecked")
207     @Test
208     public void testvDnsPolicy() {
209         //
210         // Now load the vDNS Policy - make sure
211         // the pdp can support it and have it load
212         // into the PDP.
213         //
214         assertThatCode(() -> {
215             try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.input.yaml")) {
216                 Yaml yaml = new Yaml();
217                 Map<String, Object> toscaObject = yaml.load(is);
218                 List<Object> policies = (List<Object>) toscaObject.get("policies");
219                 //
220                 // What we should really do is split the policies out from the ones that
221                 // are not supported to ones that are. And then load these.
222                 //
223                 // In another future review....
224                 //
225                 for (Object policyObject : policies) {
226                     //
227                     // Get the contents
228                     //
229                     Map<String, Object> policyContents = (Map<String, Object>) policyObject;
230                     for (Entry<String, Object> entrySet : policyContents.entrySet()) {
231                         LOGGER.info("Entry set {}", entrySet.getKey());
232                         Map<String, Object> policyDefinition = (Map<String, Object>) entrySet.getValue();
233                         //
234                         // Find the type and make sure the engine supports it
235                         //
236                         assertThat(policyDefinition.containsKey("type")).isTrue();
237                         assertThat(service.canSupportPolicyType(
238                                 policyDefinition.get("type").toString(),
239                                 policyDefinition.get("version").toString()))
240                             .isTrue();
241                     }
242                 }
243                 //
244                 // Just go ahead and load them all for now
245                 //
246                 // Assuming all are supported etc.
247                 //
248                 service.loadPolicies(toscaObject);
249                 //
250                 // Ask for a decision
251                 //
252                 DecisionResponse response = service.makeDecision(requestSinglePolicy);
253                 LOGGER.info("Decision {}", response);
254
255                 assertThat(response).isNotNull();
256                 assertThat(response.getPolicies().size()).isEqualTo(1);
257                 //
258                 // Dump it out as Json
259                 //
260                 LOGGER.info(gsonDecisionResponse.toJson(response));
261             }
262         }).doesNotThrowAnyException();
263     }
264
265     @Test
266     public void testBadPolicies() {
267         //
268         // No need for service, just test some of the methods
269         // for bad policies
270         //
271         MonitoringPdpApplication onapPdpEngine = new MonitoringPdpApplication();
272
273         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
274             try (InputStream is =
275                     new FileInputStream("src/test/resources/test.monitoring.policy.missingmetadata.yaml")) {
276                 onapPdpEngine.convertPolicies(is);
277             }
278         }).withMessageContaining("missing metadata section");
279
280         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
281             try (InputStream is =
282                     new FileInputStream("src/test/resources/test.monitoring.policy.missingtype.yaml")) {
283                 onapPdpEngine.convertPolicies(is);
284             }
285         }).withMessageContaining("missing type value");
286
287         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
288             try (InputStream is =
289                     new FileInputStream("src/test/resources/test.monitoring.policy.missingversion.yaml")) {
290                 onapPdpEngine.convertPolicies(is);
291             }
292         }).withMessageContaining("missing version value");
293
294         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
295             try (InputStream is =
296                     new FileInputStream("src/test/resources/test.monitoring.policy.badmetadata.1.yaml")) {
297                 onapPdpEngine.convertPolicies(is);
298             }
299         }).withMessageContaining("missing metadata policy-version");
300
301         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
302             try (InputStream is =
303                     new FileInputStream("src/test/resources/test.monitoring.policy.badmetadata.2.yaml")) {
304                 onapPdpEngine.convertPolicies(is);
305             }
306         }).withMessageContaining("missing metadata policy-id");
307     }
308
309 }