2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2023 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.guard;
26 import static org.assertj.core.api.Assertions.assertThat;
28 import com.att.research.xacml.api.Response;
29 import jakarta.persistence.EntityManager;
30 import jakarta.persistence.Persistence;
32 import java.io.IOException;
33 import java.time.Instant;
34 import java.util.Date;
35 import java.util.Iterator;
37 import java.util.Properties;
38 import java.util.ServiceLoader;
39 import java.util.UUID;
40 import org.apache.commons.lang3.tuple.Pair;
41 import org.junit.AfterClass;
42 import org.junit.Before;
43 import org.junit.BeforeClass;
44 import org.junit.ClassRule;
45 import org.junit.FixMethodOrder;
46 import org.junit.Test;
47 import org.junit.rules.TemporaryFolder;
48 import org.junit.runners.MethodSorters;
49 import org.onap.policy.common.utils.coder.CoderException;
50 import org.onap.policy.common.utils.coder.StandardCoder;
51 import org.onap.policy.common.utils.resources.TextFileUtils;
52 import org.onap.policy.guard.OperationsHistory;
53 import org.onap.policy.models.decisions.concepts.DecisionRequest;
54 import org.onap.policy.models.decisions.concepts.DecisionResponse;
55 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
56 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
57 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
58 import org.onap.policy.pdp.xacml.application.common.operationshistory.CountRecentOperationsPip;
59 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
63 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
64 public class SonCoordinationTest {
66 private static final Logger LOGGER = LoggerFactory.getLogger(SonCoordinationTest.class);
67 private static Properties properties = new Properties();
68 private static File propertiesFile;
69 private static XacmlApplicationServiceProvider service;
70 private static DecisionRequest requestVpciNode1;
71 private static DecisionRequest requestVsonhNode1;
72 private static StandardCoder gson = new StandardCoder();
73 private static EntityManager em;
74 private static final String DENY = "Deny";
75 private static final String PERMIT = "Permit";
78 public static final TemporaryFolder policyFolder = new TemporaryFolder();
81 * Copies the xacml.properties and policies files into
82 * temporary folder and loads the service provider saving
83 * instance of provider off for other tests to use.
86 public static void setup() throws Exception {
87 LOGGER.info("Setting up class");
89 // Setup our temporary folder
91 XacmlPolicyUtils.FileCreator myCreator =
92 (String filename) -> policyFolder.newFile(filename);
93 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
94 "src/test/resources/xacml.properties", properties, myCreator);
98 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
99 ServiceLoader.load(XacmlApplicationServiceProvider.class);
101 // Find the guard service application and save for use in all the tests
103 StringBuilder strDump =
104 new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
105 Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
106 while (iterator.hasNext()) {
107 XacmlApplicationServiceProvider application = iterator.next();
109 // Is it our service?
111 if (application instanceof GuardPdpApplication) {
113 // Should be the first and only one
115 assertThat(service).isNull();
116 service = application;
118 strDump.append(application.applicationName());
119 strDump.append(" supports ");
120 strDump.append(application.supportedPolicyTypes());
121 strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
123 LOGGER.info("{}", strDump);
125 // Tell it to initialize based on the properties file
126 // we just built for it.
128 service.initialize(propertiesFile.toPath().getParent(), null);
130 // Load Decision Requests
132 requestVpciNode1 = gson.decode(
133 TextFileUtils.getTextFileAsString(
134 "src/test/resources/requests/coordination.cl.vPci.node.1.json"),
135 DecisionRequest.class);
136 requestVsonhNode1 = gson.decode(
137 TextFileUtils.getTextFileAsString(
138 "src/test/resources/requests/coordination.cl.vSonh.node.1.json"),
139 DecisionRequest.class);
140 String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
142 .createEntityManagerFactory(SonCoordinationTest.properties.getProperty(persistenceUnit),
144 .createEntityManager();
148 * Clears the database before each test.
152 public void startClean() throws Exception {
153 em.getTransaction().begin();
154 em.createQuery("DELETE FROM OperationsHistory").executeUpdate();
155 em.getTransaction().commit();
159 * Close the entity manager.
162 public static void cleanup() throws Exception {
169 * Check that decision matches expectation.
171 * @param expected from the response
172 * @param response received
175 public void checkDecision(String expected, DecisionResponse response) throws CoderException {
176 LOGGER.info("Looking for {} Decision", expected);
177 assertThat(response).isNotNull();
178 assertThat(response.getStatus()).isNotNull();
179 assertThat(response.getStatus()).isEqualTo(expected);
181 // Dump it out as Json
183 LOGGER.info(gson.encode(response));
187 * Request a decision and check that it matches expectation.
189 * @param request to send to Xacml PDP
190 * @param expected from the response
193 public void requestAndCheckDecision(DecisionRequest request, String expected)
194 throws CoderException {
197 // Ask for a decision
199 Pair<DecisionResponse, Response> decision = service.makeDecision(request, null);
203 checkDecision(expected, decision.getKey());
207 public void test1() throws CoderException, IOException, XacmlApplicationException {
208 LOGGER.info("**************** Running vPci and vSonh Control Loops ****************");
210 // Now load the test coordination policy - make sure
211 // the pdp can support it and have it load
214 TestUtils.loadPolicies(
215 "src/test/resources/test.policy.guard.coordination.vPciBlocksVsonh.tosca.yaml",
217 TestUtils.loadPolicies(
218 "src/test/resources/test.policy.guard.coordination.vSonhBlocksVpci.tosca.yaml",
221 // vSonh doesn't have open action: vPci should get permit
223 requestAndCheckDecision(requestVpciNode1, PERMIT);
225 // vPci doesn't have open action: vSonh should get permit
227 requestAndCheckDecision(requestVsonhNode1, PERMIT);
229 // Open vSonh on node1
231 long vsonhId = insertOperationEvent(requestVsonhNode1, "Started");
233 // Under current coordination policy vPci should get a deny
235 requestAndCheckDecision(requestVpciNode1, DENY);
237 // Close vSonh on node1
239 updateOperationEvent(vsonhId, "Success");
241 // With vSonh closed on node 1, vPci now should get a permit
243 requestAndCheckDecision(requestVpciNode1, PERMIT);
245 // Open vPci on node1
247 long vpciId = insertOperationEvent(requestVpciNode1, "Started");
249 // Under current coordination policy vSonh should get a deny
251 requestAndCheckDecision(requestVsonhNode1, DENY);
253 // Close cl1 on node1
255 updateOperationEvent(vpciId, "Failed");
257 // With vPci closed on node 1, vSonh now should get a permit
259 requestAndCheckDecision(requestVsonhNode1, PERMIT);
262 @SuppressWarnings("unchecked")
263 private long insertOperationEvent(DecisionRequest request, String outcome) {
265 // Get the properties
267 Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
271 OperationsHistory newEntry = new OperationsHistory();
272 newEntry.setActor(properties.get("actor").toString());
273 newEntry.setOperation(properties.get("operation").toString());
274 newEntry.setClosedLoopName(properties.get("clname").toString());
275 newEntry.setOutcome(outcome);
276 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
277 newEntry.setEndtime(Date.from(Instant.now()));
278 newEntry.setRequestId(UUID.randomUUID().toString());
279 newEntry.setTarget(properties.get("target").toString());
280 em.getTransaction().begin();
281 em.persist(newEntry);
282 em.getTransaction().commit();
283 return newEntry.getId();
286 private void updateOperationEvent(long id, String outcome) {
288 OperationsHistory updateEntry = em.find(OperationsHistory.class, id);
289 updateEntry.setOutcome(outcome);
290 updateEntry.setEndtime(Date.from(Instant.now()));
291 em.getTransaction().begin();
292 em.persist(updateEntry);
293 em.getTransaction().commit();