2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
6 Modifications Copyright (C) 2019 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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.xacml.pdp.application.optimization;
26 import static org.assertj.core.api.Assertions.assertThat;
27 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
28 import static org.mockito.Mockito.mock;
29 import static org.mockito.Mockito.when;
31 import com.att.research.xacml.api.Response;
32 import com.google.common.collect.Lists;
34 import java.nio.file.Files;
35 import java.nio.file.Paths;
36 import java.util.Collection;
37 import java.util.Iterator;
38 import java.util.List;
40 import java.util.Map.Entry;
41 import java.util.Properties;
42 import java.util.ServiceLoader;
43 import org.apache.commons.lang3.tuple.Pair;
44 import org.assertj.core.api.Condition;
45 import org.junit.BeforeClass;
46 import org.junit.ClassRule;
47 import org.junit.FixMethodOrder;
48 import org.junit.Test;
49 import org.junit.rules.TemporaryFolder;
50 import org.junit.runners.MethodSorters;
51 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
52 import org.onap.policy.common.utils.coder.CoderException;
53 import org.onap.policy.common.utils.coder.StandardCoder;
54 import org.onap.policy.common.utils.coder.StandardYamlCoder;
55 import org.onap.policy.common.utils.resources.ResourceUtils;
56 import org.onap.policy.common.utils.resources.TextFileUtils;
57 import org.onap.policy.models.decisions.concepts.DecisionRequest;
58 import org.onap.policy.models.decisions.concepts.DecisionResponse;
59 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
60 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
61 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
62 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
63 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
64 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
65 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
66 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
70 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
71 public class OptimizationPdpApplicationTest {
73 private static final Logger LOGGER = LoggerFactory.getLogger(OptimizationPdpApplicationTest.class);
74 private static Properties properties = new Properties();
75 private static File propertiesFile;
76 private static XacmlApplicationServiceProvider service;
77 private static StandardCoder gson = new StandardCoder();
78 private static DecisionRequest baseRequest;
79 private static RestServerParameters clientParams;
80 private static String[] listPolicyTypeFiles = {
81 "onap.policies.Optimization",
82 "onap.policies.optimization.Resource",
83 "onap.policies.optimization.Service",
84 "onap.policies.optimization.resource.AffinityPolicy",
85 "onap.policies.optimization.resource.DistancePolicy",
86 "onap.policies.optimization.resource.HpaPolicy",
87 "onap.policies.optimization.resource.OptimizationPolicy",
88 "onap.policies.optimization.resource.PciPolicy",
89 "onap.policies.optimization.service.QueryPolicy",
90 "onap.policies.optimization.service.SubscriberPolicy",
91 "onap.policies.optimization.resource.Vim_fit",
92 "onap.policies.optimization.resource.VnfPolicy"};
95 public static final TemporaryFolder policyFolder = new TemporaryFolder();
98 * Copies the xacml.properties and policies files into
99 * temporary folder and loads the service provider saving
100 * instance of provider off for other tests to use.
103 public static void setUp() throws Exception {
104 clientParams = mock(RestServerParameters.class);
105 when(clientParams.getHost()).thenReturn("localhost");
106 when(clientParams.getPort()).thenReturn(6969);
108 // Load Single Decision Request
110 baseRequest = gson.decode(
112 .getTextFileAsString(
113 "src/test/resources/decision.optimization.input.json"),
114 DecisionRequest.class);
116 // Setup our temporary folder
118 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
119 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
120 properties, myCreator);
122 // Copy the test policy types into data area
124 for (String policy : listPolicyTypeFiles) {
125 String policyType = ResourceUtils.getResourceAsString("policytypes/" + policy + ".yaml");
126 LOGGER.info("Copying {}", policyType);
127 Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
128 policyType.getBytes());
133 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
134 ServiceLoader.load(XacmlApplicationServiceProvider.class);
136 // Iterate through Xacml application services and find
137 // the optimization service. Save it for use throughout
138 // all the Junit tests.
140 StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
141 Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
142 while (iterator.hasNext()) {
143 XacmlApplicationServiceProvider application = iterator.next();
145 // Is it our service?
147 if (application instanceof OptimizationPdpApplication) {
149 // Should be the first and only one
151 assertThat(service).isNull();
152 service = application;
154 strDump.append(application.applicationName());
155 strDump.append(" supports ");
156 strDump.append(application.supportedPolicyTypes());
157 strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
159 LOGGER.debug("{}", strDump);
160 assertThat(service).isNotNull();
162 // Tell it to initialize based on the properties file
163 // we just built for it.
165 service.initialize(propertiesFile.toPath().getParent(), clientParams);
169 * Simply test some of the simple methods for the application.
172 public void test01Basics() {
174 // Make sure there's an application name
176 assertThat(service.applicationName()).isNotEmpty();
178 // Does it return the correct decisions
180 assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
181 assertThat(service.actionDecisionsSupported()).contains("optimize");
183 // Ensure it has the supported policy types and
184 // can support the correct policy types.
186 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
187 "onap.policies.optimization.resource.AffinityPolicy", "1.0.0"))).isTrue();
188 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
189 "onap.policies.optimization.service.SubscriberPolicy", "1.0.0"))).isTrue();
190 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
191 "onap.foobar", "1.0.0"))).isFalse();
195 * With no policies loaded, there should be 0 policies returned.
197 * @throws CoderException CoderException
200 public void test02NoPolicies() throws CoderException {
202 // Ask for a decision when there are no policies loaded
204 LOGGER.info("Request {}", gson.encode(baseRequest));
205 Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
206 LOGGER.info("Decision {}", decision.getKey());
208 assertThat(decision.getKey()).isNotNull();
209 assertThat(decision.getKey().getPolicies().size()).isEqualTo(0);
213 * Should return ONLY default policies.
215 * @throws XacmlApplicationException could not load policies
218 public void test03OptimizationDefault() throws XacmlApplicationException {
220 // Now load all the optimization policies
222 List<ToscaPolicy> loadedPolicies = TestUtils.loadPolicies("src/test/resources/test-optimization-policies.yaml",
224 assertThat(loadedPolicies).isNotNull();
225 assertThat(loadedPolicies).hasSize(14);
227 // Ask for a decision for available default policies
229 DecisionResponse response = makeDecision();
231 assertThat(response).isNotNull();
232 assertThat(response.getPolicies().size()).isEqualTo(2);
236 validateDecision(response, baseRequest);
240 * Should only return default HPA policy type.
242 @SuppressWarnings("unchecked")
244 public void test04OptimizationDefaultHpa() {
246 // Add in policy type
248 List<String> policyTypes = Lists.newArrayList("onap.policies.optimization.resource.HpaPolicy");
249 baseRequest.getResource().put("policy-type", policyTypes);
251 // Ask for a decision for default HPA policy
253 DecisionResponse response = makeDecision();
255 assertThat(response).isNotNull();
256 assertThat(response.getPolicies().size()).isEqualTo(1);
257 response.getPolicies().forEach((key, value) -> {
258 assertThat(((Map<String, Object>) value).get("type"))
259 .isEqualTo(("onap.policies.optimization.resource.HpaPolicy"));
264 validateDecision(response, baseRequest);
268 * Refine for US only policies.
270 @SuppressWarnings("unchecked")
272 public void test05OptimizationDefaultGeography() throws CoderException {
274 // Remove all the policy-type resources from the request
278 // Add US to the geography list
280 ((List<String>)baseRequest.getResource().get("geography")).add("US");
282 // Ask for a decision for default US Policy
284 DecisionResponse response = makeDecision();
285 assertThat(response).isNotNull();
286 assertThat(response.getPolicies().size()).isEqualTo(2);
290 validateDecision(response, baseRequest);
294 * Add more refinement for service.
296 @SuppressWarnings("unchecked")
298 public void test06OptimizationDefaultGeographyAndService() {
300 // Add vCPE to the service list
302 ((List<String>)baseRequest.getResource().get("services")).add("vCPE");
304 // Ask for a decision for default US policy for vCPE service
306 DecisionResponse response = makeDecision();
308 assertThat(response).isNotNull();
309 assertThat(response.getPolicies().size()).isEqualTo(3);
313 validateDecision(response, baseRequest);
317 * Add more refinement for specific resource.
319 @SuppressWarnings("unchecked")
321 public void test07OptimizationDefaultGeographyAndServiceAndResource() {
323 // Add vG to the resource list
325 ((List<String>)baseRequest.getResource().get("resources")).add("vG");
327 // Ask for a decision for default US service vCPE resource vG policy
329 DecisionResponse response = makeDecision();
331 assertThat(response).isNotNull();
332 assertThat(response.getPolicies().size()).isEqualTo(6);
336 validateDecision(response, baseRequest);
340 * Now we need to add in subscriberName in order to get scope for gold.
342 @SuppressWarnings("unchecked")
344 public void test08OptimizationGeographyAndServiceAndResourceAndScopeIsGoldSubscriber() {
346 // Add gold as a scope
348 ((List<String>)baseRequest.getContext().get("subscriberName")).add("subscriber_a");
350 // Ask for a decision for specific US vCPE vG gold
352 DecisionResponse response = makeDecision();
354 assertThat(response).isNotNull();
355 assertThat(response.getPolicies()).hasSize(6);
356 assertThat(response.getAdvice()).hasSize(2);
360 validateDecision(response, baseRequest);
364 * Add a subscriber that should be platinum.
366 @SuppressWarnings("unchecked")
368 public void test09OptimizationGeographyAndServiceAndResourceAndScopeGoldOrPlatinumSubscriber() {
370 // Add platinum to the scope list: this is now gold OR platinum
372 ((List<String>)baseRequest.getResource().get("scope")).remove("gold");
373 ((List<String>)baseRequest.getContext().get("subscriberName")).add("subscriber_x");
375 // Ask for a decision for specific US vCPE vG (gold or platinum)
377 DecisionResponse response = makeDecision();
379 assertThat(response).isNotNull();
380 assertThat(response.getPolicies()).hasSize(8);
381 assertThat(response.getAdvice()).hasSize(2);
385 validateDecision(response, baseRequest);
389 * Remove gold subscriber, keep the platinum one.
391 @SuppressWarnings("unchecked")
393 public void test10OptimizationGeographyAndServiceAndResourceAndScopeNotGoldStillPlatinum() {
395 // Add gold as a scope
397 ((List<String>)baseRequest.getResource().get("scope")).remove("gold");
398 ((List<String>)baseRequest.getResource().get("scope")).remove("platinum");
399 ((List<String>)baseRequest.getContext().get("subscriberName")).remove("subscriber_a");
401 // Ask for a decision for specific US vCPE vG gold
403 DecisionResponse response = makeDecision();
405 assertThat(response).isNotNull();
406 assertThat(response.getPolicies().size()).isEqualTo(7);
410 validateDecision(response, baseRequest);
414 * Filter by Affinity policy.
417 public void test11OptimizationPolicyTypeDefault() {
419 // Add in policy type
421 List<String> policyTypes = Lists.newArrayList("onap.policies.optimization.resource.AffinityPolicy");
422 baseRequest.getResource().put("policy-type", policyTypes);
424 // Ask for a decision for default
426 DecisionResponse response = makeDecision();
428 assertThat(response).isNotNull();
429 assertThat(response.getPolicies().size()).isEqualTo(1);
433 validateDecision(response, baseRequest);
437 * Now filter by HPA policy type.
439 @SuppressWarnings("unchecked")
441 public void test12OptimizationPolicyTypeDefault() {
443 // Add in another policy type
445 ((List<String>) baseRequest.getResource().get("policy-type"))
446 .add("onap.policies.optimization.resource.HpaPolicy");
448 // Ask for a decision for default
450 DecisionResponse response = makeDecision();
452 assertThat(response).isNotNull();
453 assertThat(response.getPolicies().size()).isEqualTo(2);
457 validateDecision(response, baseRequest);
461 public void test999BadSubscriberPolicies() throws Exception {
462 final StandardYamlCoder yamlCoder = new StandardYamlCoder();
466 String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/bad-subscriber-policies.yaml");
468 // Serialize it into a class
470 ToscaServiceTemplate serviceTemplate;
472 serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
473 } catch (CoderException e) {
474 throw new XacmlApplicationException("Failed to decode policy from resource file", e);
477 // Make sure all the fields are setup properly
479 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
480 jtst.fromAuthorative(serviceTemplate);
481 ToscaServiceTemplate completedJtst = jtst.toAuthorative();
485 for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
486 for (ToscaPolicy policy : policies.values()) {
487 if ("missing-subscriberProperties".equals(policy.getName())) {
488 assertThatExceptionOfType(XacmlApplicationException.class).isThrownBy(() ->
489 service.loadPolicy(policy));
490 } else if ("missing-subscriberName".equals(policy.getName())) {
491 assertThatExceptionOfType(XacmlApplicationException.class).isThrownBy(() ->
492 service.loadPolicy(policy));
493 } else if ("missing-subscriberRole".equals(policy.getName())) {
494 assertThatExceptionOfType(XacmlApplicationException.class).isThrownBy(() ->
495 service.loadPolicy(policy));
501 private DecisionResponse makeDecision() {
502 Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
503 LOGGER.info("Request Resources {}", baseRequest.getResource());
504 LOGGER.info("Decision {}", decision.getKey());
505 for (Entry<String, Object> entrySet : decision.getKey().getPolicies().entrySet()) {
506 LOGGER.info("Policy {}", entrySet.getKey());
508 return decision.getKey();
511 @SuppressWarnings("unchecked")
512 private void validateDecision(DecisionResponse decision, DecisionRequest request) {
513 for (Entry<String, Object> entrySet : decision.getPolicies().entrySet()) {
514 LOGGER.info("Decision Returned Policy {}", entrySet.getKey());
515 assertThat(entrySet.getValue()).isInstanceOf(Map.class);
516 Map<String, Object> policyContents = (Map<String, Object>) entrySet.getValue();
517 assertThat(policyContents.containsKey("properties")).isTrue();
518 assertThat(policyContents.get("properties")).isInstanceOf(Map.class);
519 Map<String, Object> policyProperties = (Map<String, Object>) policyContents.get("properties");
521 validateMatchable((Collection<String>) request.getResource().get("scope"),
522 (Collection<String>) policyProperties.get("scope"));
524 validateMatchable((Collection<String>) request.getResource().get("services"),
525 (Collection<String>) policyProperties.get("services"));
527 validateMatchable((Collection<String>) request.getResource().get("resources"),
528 (Collection<String>) policyProperties.get("resources"));
530 validateMatchable((Collection<String>) request.getResource().get("geography"),
531 (Collection<String>) policyProperties.get("geography"));
535 private void validateMatchable(Collection<String> requestList, Collection<String> policyProperties) {
536 LOGGER.info("Validating matchable: {} with {}", policyProperties, requestList);
538 // Null or empty implies '*' - that is any value is acceptable
541 if (policyProperties == null || policyProperties.isEmpty()) {
544 Condition<String> condition = new Condition<>(
545 requestList::contains,
546 "Request list is contained");
547 assertThat(policyProperties).haveAtLeast(1, condition);
551 @SuppressWarnings("unchecked")
552 private void cleanOutResources() {
553 ((List<String>)baseRequest.getResource().get("scope")).clear();
554 ((List<String>)baseRequest.getResource().get("services")).clear();
555 ((List<String>)baseRequest.getResource().get("resources")).clear();
556 ((List<String>)baseRequest.getResource().get("geography")).clear();
557 if (((List<String>)baseRequest.getResource().get("policy-type")) != null) {
558 baseRequest.getResource().remove("policy-type");