11a7a923296a0221a7417813fdf17a384deaa93f
[policy/xacml-pdp.git] /
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.optimization;
24
25 import static org.assertj.core.api.Assertions.assertThat;
26 import static org.mockito.Mockito.mock;
27 import static org.mockito.Mockito.when;
28
29 import com.att.research.xacml.api.Response;
30 import java.io.File;
31 import java.io.FileNotFoundException;
32 import java.io.IOException;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
35 import java.util.Iterator;
36 import java.util.Properties;
37 import java.util.ServiceLoader;
38 import org.apache.commons.lang3.tuple.Pair;
39 import org.junit.BeforeClass;
40 import org.junit.ClassRule;
41 import org.junit.FixMethodOrder;
42 import org.junit.Test;
43 import org.junit.rules.TemporaryFolder;
44 import org.junit.runners.MethodSorters;
45 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
46 import org.onap.policy.common.utils.coder.CoderException;
47 import org.onap.policy.common.utils.coder.StandardCoder;
48 import org.onap.policy.common.utils.resources.ResourceUtils;
49 import org.onap.policy.common.utils.resources.TextFileUtils;
50 import org.onap.policy.models.decisions.concepts.DecisionRequest;
51 import org.onap.policy.models.decisions.concepts.DecisionResponse;
52 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
53 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
54 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
55 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
56 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
61 public class OptimizationPdpApplicationTest {
62
63     private static final Logger LOGGER = LoggerFactory.getLogger(OptimizationPdpApplicationTest.class);
64     private static Properties properties = new Properties();
65     private static File propertiesFile;
66     private static XacmlApplicationServiceProvider service;
67     private static StandardCoder gson = new StandardCoder();
68     private static DecisionRequest requestAffinity;
69     private static RestServerParameters clientParams;
70     private static String[] listPolicyTypeFiles = {
71         "onap.policies.Optimization",
72         "onap.policies.optimization.AffinityPolicy",
73         "onap.policies.optimization.DistancePolicy",
74         "onap.policies.optimization.HpaPolicy",
75         "onap.policies.optimization.OptimizationPolicy",
76         "onap.policies.optimization.PciPolicy",
77         "onap.policies.optimization.QueryPolicy",
78         "onap.policies.optimization.SubscriberPolicy",
79         "onap.policies.optimization.Vim_fit",
80         "onap.policies.optimization.VnfPolicy"};
81
82     @ClassRule
83     public static final TemporaryFolder policyFolder = new TemporaryFolder();
84
85     /**
86      * Copies the xacml.properties and policies files into
87      * temporary folder and loads the service provider saving
88      * instance of provider off for other tests to use.
89      */
90     @BeforeClass
91     public static void setUp() throws Exception {
92         clientParams = mock(RestServerParameters.class);
93         when(clientParams.getHost()).thenReturn("localhost");
94         when(clientParams.getPort()).thenReturn(6969);
95         //
96         // Load Single Decision Request
97         //
98         requestAffinity = gson.decode(
99                 TextFileUtils
100                     .getTextFileAsString(
101                             "../../main/src/test/resources/decisions/decision.optimization.affinity.input.json"),
102                     DecisionRequest.class);
103         //
104         // Setup our temporary folder
105         //
106         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
107         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
108                 properties, myCreator);
109         //
110         // Copy the test policy types into data area
111         //
112         for (String policy : listPolicyTypeFiles) {
113             String policyType = ResourceUtils.getResourceAsString("policytypes/" + policy + ".yaml");
114             LOGGER.info("Copying {}", policyType);
115             Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
116                     policyType.getBytes());
117         }
118         //
119         // Load service
120         //
121         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
122                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
123         //
124         // Iterate through Xacml application services and find
125         // the optimization service. Save it for use throughout
126         // all the Junit tests.
127         //
128         StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
129         Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
130         while (iterator.hasNext()) {
131             XacmlApplicationServiceProvider application = iterator.next();
132             //
133             // Is it our service?
134             //
135             if (application instanceof OptimizationPdpApplication) {
136                 //
137                 // Should be the first and only one
138                 //
139                 assertThat(service).isNull();
140                 service = application;
141             }
142             strDump.append(application.applicationName());
143             strDump.append(" supports ");
144             strDump.append(application.supportedPolicyTypes());
145             strDump.append(System.lineSeparator());
146         }
147         LOGGER.debug("{}", strDump);
148         assertThat(service).isNotNull();
149         //
150         // Tell it to initialize based on the properties file
151         // we just built for it.
152         //
153         service.initialize(propertiesFile.toPath().getParent(), clientParams);
154     }
155
156     @Test
157     public void test1Basics() {
158         //
159         // Make sure there's an application name
160         //
161         assertThat(service.applicationName()).isNotEmpty();
162         //
163         // Decisions
164         //
165         assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
166         assertThat(service.actionDecisionsSupported()).contains("optimize");
167         //
168         // Ensure it has the supported policy types and
169         // can support the correct policy types.
170         //
171         assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
172                 "onap.policies.optimization.AffinityPolicy", "1.0.0"))).isTrue();
173         assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
174                 "onap.foobar", "1.0.0"))).isFalse();
175     }
176
177     @Test
178     public void test2NoPolicies() {
179         //
180         // Ask for a decision
181         //
182         Pair<DecisionResponse, Response> decision = service.makeDecision(requestAffinity, null);
183         LOGGER.info("Decision {}", decision.getKey());
184
185         assertThat(decision.getKey()).isNotNull();
186         assertThat(decision.getKey().getPolicies().size()).isEqualTo(0);
187     }
188
189     @Test
190     public void test3AddOptimizationPolicies() throws CoderException, FileNotFoundException, IOException,
191         XacmlApplicationException {
192         //
193         // Now load the optimization policies
194         //
195         TestUtils.loadPolicies("src/test/resources/vCPE.policies.optimization.input.tosca.yaml", service);
196         //
197         // Ask for a decision
198         //
199         Pair<DecisionResponse, Response> decision = service.makeDecision(requestAffinity, null);
200         LOGGER.info("Decision {}", decision.getKey());
201
202         assertThat(decision.getKey()).isNotNull();
203         assertThat(decision.getKey().getPolicies().size()).isEqualTo(4);
204         //
205         // Dump it out as Json
206         //
207         LOGGER.info(gson.encode(decision.getKey()));
208     }
209 }