2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2020-2021 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.guard;
25 import static org.assertj.core.api.Assertions.assertThat;
27 import com.att.research.xacml.api.Response;
29 import java.io.IOException;
30 import java.time.Instant;
31 import java.util.Date;
32 import java.util.Iterator;
34 import java.util.Properties;
35 import java.util.ServiceLoader;
36 import java.util.UUID;
37 import javax.persistence.EntityManager;
38 import javax.persistence.Persistence;
39 import org.apache.commons.lang3.tuple.Pair;
40 import org.junit.AfterClass;
41 import org.junit.Before;
42 import org.junit.BeforeClass;
43 import org.junit.ClassRule;
44 import org.junit.FixMethodOrder;
45 import org.junit.Test;
46 import org.junit.rules.TemporaryFolder;
47 import org.junit.runners.MethodSorters;
48 import org.onap.policy.common.utils.coder.CoderException;
49 import org.onap.policy.common.utils.coder.StandardCoder;
50 import org.onap.policy.common.utils.resources.TextFileUtils;
51 import org.onap.policy.guard.OperationsHistory;
52 import org.onap.policy.models.decisions.concepts.DecisionRequest;
53 import org.onap.policy.models.decisions.concepts.DecisionResponse;
54 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
55 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
56 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
57 import org.onap.policy.pdp.xacml.application.common.operationshistory.CountRecentOperationsPip;
58 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
63 public class SonCoordinationTest {
65 private static final Logger LOGGER = LoggerFactory.getLogger(SonCoordinationTest.class);
66 private static Properties properties = new Properties();
67 private static File propertiesFile;
68 private static XacmlApplicationServiceProvider service;
69 private static DecisionRequest requestVpciNode1;
70 private static DecisionRequest requestVsonhNode1;
71 private static StandardCoder gson = new StandardCoder();
72 private static EntityManager em;
73 private static final String DENY = "Deny";
74 private static final String PERMIT = "Permit";
77 public static final TemporaryFolder policyFolder = new TemporaryFolder();
80 * Copies the xacml.properties and policies files into
81 * temporary folder and loads the service provider saving
82 * instance of provider off for other tests to use.
85 public static void setup() throws Exception {
86 LOGGER.info("Setting up class");
88 // Setup our temporary folder
90 XacmlPolicyUtils.FileCreator myCreator =
91 (String filename) -> policyFolder.newFile(filename);
92 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
93 "src/test/resources/xacml.properties", properties, myCreator);
97 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
98 ServiceLoader.load(XacmlApplicationServiceProvider.class);
100 // Find the guard service application and save for use in all the tests
102 StringBuilder strDump =
103 new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
104 Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
105 while (iterator.hasNext()) {
106 XacmlApplicationServiceProvider application = iterator.next();
108 // Is it our service?
110 if (application instanceof GuardPdpApplication) {
112 // Should be the first and only one
114 assertThat(service).isNull();
115 service = application;
117 strDump.append(application.applicationName());
118 strDump.append(" supports ");
119 strDump.append(application.supportedPolicyTypes());
120 strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
122 LOGGER.info("{}", strDump);
124 // Tell it to initialize based on the properties file
125 // we just built for it.
127 service.initialize(propertiesFile.toPath().getParent(), null);
129 // Load Decision Requests
131 requestVpciNode1 = gson.decode(
132 TextFileUtils.getTextFileAsString(
133 "src/test/resources/requests/coordination.cl.vPci.node.1.json"),
134 DecisionRequest.class);
135 requestVsonhNode1 = gson.decode(
136 TextFileUtils.getTextFileAsString(
137 "src/test/resources/requests/coordination.cl.vSonh.node.1.json"),
138 DecisionRequest.class);
139 String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
141 .createEntityManagerFactory(SonCoordinationTest.properties.getProperty(persistenceUnit),
143 .createEntityManager();
147 * Clears the database before each test.
151 public void startClean() throws Exception {
152 em.getTransaction().begin();
153 em.createQuery("DELETE FROM OperationsHistory").executeUpdate();
154 em.getTransaction().commit();
158 * Close the entity manager.
161 public static void cleanup() throws Exception {
168 * Check that decision matches expectation.
170 * @param expected from the response
171 * @param response received
174 public void checkDecision(String expected, DecisionResponse response) throws CoderException {
175 LOGGER.info("Looking for {} Decision", expected);
176 assertThat(response).isNotNull();
177 assertThat(response.getStatus()).isNotNull();
178 assertThat(response.getStatus()).isEqualTo(expected);
180 // Dump it out as Json
182 LOGGER.info(gson.encode(response));
186 * Request a decision and check that it matches expectation.
188 * @param request to send to Xacml PDP
189 * @param expected from the response
192 public void requestAndCheckDecision(DecisionRequest request, String expected)
193 throws CoderException {
196 // Ask for a decision
198 Pair<DecisionResponse, Response> decision = service.makeDecision(request, null);
202 checkDecision(expected, decision.getKey());
206 public void test1() throws CoderException, IOException, XacmlApplicationException {
207 LOGGER.info("**************** Running vPci and vSonh Control Loops ****************");
209 // Now load the test coordination policy - make sure
210 // the pdp can support it and have it load
213 TestUtils.loadPolicies(
214 "src/test/resources/test.policy.guard.coordination.vPciBlocksVsonh.tosca.yaml",
216 TestUtils.loadPolicies(
217 "src/test/resources/test.policy.guard.coordination.vSonhBlocksVpci.tosca.yaml",
220 // vSonh doesn't have open action: vPci should get permit
222 requestAndCheckDecision(requestVpciNode1, PERMIT);
224 // vPci doesn't have open action: vSonh should get permit
226 requestAndCheckDecision(requestVsonhNode1, PERMIT);
228 // Open vSonh on node1
230 long vsonhId = insertOperationEvent(requestVsonhNode1, "Started");
232 // Under current coordination policy vPci should get a deny
234 requestAndCheckDecision(requestVpciNode1, DENY);
236 // Close vSonh on node1
238 updateOperationEvent(vsonhId, "Success");
240 // With vSonh closed on node 1, vPci now should get a permit
242 requestAndCheckDecision(requestVpciNode1, PERMIT);
244 // Open vPci on node1
246 long vpciId = insertOperationEvent(requestVpciNode1, "Started");
248 // Under current coordination policy vSonh should get a deny
250 requestAndCheckDecision(requestVsonhNode1, DENY);
252 // Close cl1 on node1
254 updateOperationEvent(vpciId, "Failed");
256 // With vPci closed on node 1, vSonh now should get a permit
258 requestAndCheckDecision(requestVsonhNode1, PERMIT);
261 @SuppressWarnings("unchecked")
262 private long insertOperationEvent(DecisionRequest request, String outcome) {
264 // Get the properties
266 Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
270 OperationsHistory newEntry = new OperationsHistory();
271 newEntry.setActor(properties.get("actor").toString());
272 newEntry.setOperation(properties.get("operation").toString());
273 newEntry.setClosedLoopName(properties.get("clname").toString());
274 newEntry.setOutcome(outcome);
275 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
276 newEntry.setEndtime(Date.from(Instant.now()));
277 newEntry.setRequestId(UUID.randomUUID().toString());
278 newEntry.setTarget(properties.get("target").toString());
279 em.getTransaction().begin();
280 em.persist(newEntry);
281 em.getTransaction().commit();
282 return newEntry.getId();
285 private void updateOperationEvent(long id, String outcome) {
287 OperationsHistory updateEntry = em.find(OperationsHistory.class, id);
288 updateEntry.setOutcome(outcome);
289 updateEntry.setEndtime(Date.from(Instant.now()));
290 em.getTransaction().begin();
291 em.persist(updateEntry);
292 em.getTransaction().commit();