2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.xacml.pdp.application.monitoring;
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;
29 import com.att.research.xacml.util.XACMLProperties;
30 import com.google.common.io.Files;
31 import com.google.gson.Gson;
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;
43 import java.util.Map.Entry;
44 import java.util.Properties;
45 import java.util.ServiceLoader;
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;
62 public class MonitoringPdpApplicationTest {
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;
70 private static Gson gsonDecisionRequest;
71 private static Gson gsonDecisionResponse;
74 public static final TemporaryFolder policyFolder = new TemporaryFolder();
80 public static void setup() {
81 assertThatCode(() -> {
83 // Create our Gson builder
85 gsonDecisionRequest = new DecisionRequestMessageBodyHandler().getGson();
86 gsonDecisionResponse = new DecisionResponseMessageBodyHandler().getGson();
88 // Load Single Decision Request
90 requestSinglePolicy = gsonDecisionRequest.fromJson(
92 .getTextFileAsString("../../main/src/test/resources/decisions/decision.single.input.json"),
93 DecisionRequest.class);
95 // Copy all the properties and root policies to the temporary folder
97 try (InputStream is = new FileInputStream("src/test/resources/xacml.properties")) {
102 propertiesFile = policyFolder.newFile("xacml.properties");
104 // Copy the root policies
106 for (String root : XACMLProperties.getRootPolicyIDs(properties)) {
110 Path rootPath = Paths.get(properties.getProperty(root + ".file"));
111 LOGGER.debug("Root file {} {}", rootPath, rootPath.getFileName());
113 // Construct new file name
115 File newRootPath = policyFolder.newFile(rootPath.getFileName().toString());
119 Files.copy(rootPath.toFile(), newRootPath);
120 assertThat(newRootPath).exists();
122 // Point to where the new policy is in the temp dir
124 properties.setProperty(root + ".file", newRootPath.getAbsolutePath());
126 try (OutputStream os = new FileOutputStream(propertiesFile.getAbsolutePath())) {
127 properties.store(os, "");
128 assertThat(propertiesFile).exists();
134 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
135 ServiceLoader.load(XacmlApplicationServiceProvider.class);
137 // Iterate through them - I could store the object as
138 // XacmlApplicationServiceProvider pointer.
142 StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
143 Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
144 while (iterator.hasNext()) {
145 XacmlApplicationServiceProvider application = iterator.next();
147 // Is it our service?
149 if (application instanceof MonitoringPdpApplication) {
151 // Should be the first and only one
153 assertThat(service).isNull();
154 service = application;
156 strDump.append(application.applicationName());
157 strDump.append(" supports ");
158 strDump.append(application.supportedPolicyTypes());
159 strDump.append(System.lineSeparator());
161 LOGGER.debug("{}", strDump);
163 // Tell it to initialize based on the properties file
164 // we just built for it.
166 service.initialize(propertiesFile.toPath().getParent());
168 // Make sure there's an application name
170 assertThat(service.applicationName()).isNotEmpty();
172 // Ensure it has the supported policy types and
173 // can support the correct policy types.
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");
181 // Ensure it supports decisions
183 assertThat(service.actionDecisionsSupported()).contains("configure");
184 }).doesNotThrowAnyException();
188 public void testNoPolicies() {
190 // Make a simple decision - NO policies are loaded
192 assertThatCode(() -> {
194 // Ask for a decision
196 DecisionResponse response = service.makeDecision(requestSinglePolicy);
197 LOGGER.info("Decision {}", response);
199 assertThat(response).isNotNull();
200 assertThat(response.getErrorMessage()).isNullOrEmpty();
201 assertThat(response.getPolicies().size()).isEqualTo(0);
203 }).doesNotThrowAnyException();
206 @SuppressWarnings("unchecked")
208 public void testvDnsPolicy() {
210 // Now load the vDNS Policy - make sure
211 // the pdp can support it and have it load
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");
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.
223 // In another future review....
225 for (Object policyObject : policies) {
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();
234 // Find the type and make sure the engine supports it
236 assertThat(policyDefinition.containsKey("type")).isTrue();
237 assertThat(service.canSupportPolicyType(
238 policyDefinition.get("type").toString(),
239 policyDefinition.get("version").toString()))
244 // Just go ahead and load them all for now
246 // Assuming all are supported etc.
248 service.loadPolicies(toscaObject);
250 // Ask for a decision
252 DecisionResponse response = service.makeDecision(requestSinglePolicy);
253 LOGGER.info("Decision {}", response);
255 assertThat(response).isNotNull();
256 assertThat(response.getPolicies().size()).isEqualTo(1);
258 // Dump it out as Json
260 LOGGER.info(gsonDecisionResponse.toJson(response));
262 }).doesNotThrowAnyException();
266 public void testBadPolicies() {
268 // No need for service, just test some of the methods
271 MonitoringPdpApplication onapPdpEngine = new MonitoringPdpApplication();
274 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
275 try (InputStream is =
276 new FileInputStream("src/test/resources/test.monitoring.policy.missingmetadata.yaml")) {
277 onapPdpEngine.convertPolicies(is);
279 }).withMessageContaining("missing metadata section");
281 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
282 try (InputStream is =
283 new FileInputStream("src/test/resources/test.monitoring.policy.missingtype.yaml")) {
284 onapPdpEngine.convertPolicies(is);
286 }).withMessageContaining("missing type value");
288 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
289 try (InputStream is =
290 new FileInputStream("src/test/resources/test.monitoring.policy.missingversion.yaml")) {
291 onapPdpEngine.convertPolicies(is);
293 }).withMessageContaining("missing version value");
295 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
296 try (InputStream is =
297 new FileInputStream("src/test/resources/test.monitoring.policy.badmetadata.1.yaml")) {
298 onapPdpEngine.convertPolicies(is);
300 }).withMessageContaining("missing metadata policy-version");
302 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
303 try (InputStream is =
304 new FileInputStream("src/test/resources/test.monitoring.policy.badmetadata.2.yaml")) {
305 onapPdpEngine.convertPolicies(is);
307 }).withMessageContaining("missing metadata policy-id");