Upgrade Java 17 in xacml-pdp
[policy/xacml-pdp.git] / applications / guard / src / test / java / org / onap / policy / xacml / pdp / application / guard / SonCoordinationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.xacml.pdp.application.guard;
25
26 import static org.assertj.core.api.Assertions.assertThat;
27
28 import com.att.research.xacml.api.Response;
29 import jakarta.persistence.EntityManager;
30 import jakarta.persistence.Persistence;
31 import java.io.File;
32 import java.io.IOException;
33 import java.time.Instant;
34 import java.util.Date;
35 import java.util.Iterator;
36 import java.util.Map;
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;
62
63 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
64 public class SonCoordinationTest {
65
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";
76
77     @ClassRule
78     public static final TemporaryFolder policyFolder = new TemporaryFolder();
79
80     /**
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.
84      */
85     @BeforeClass
86     public static void setup() throws Exception {
87         LOGGER.info("Setting up class");
88         //
89         // Setup our temporary folder
90         //
91         XacmlPolicyUtils.FileCreator myCreator =
92             (String filename) -> policyFolder.newFile(filename);
93         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents(
94             "src/test/resources/xacml.properties", properties, myCreator);
95         //
96         // Load service
97         //
98         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
99             ServiceLoader.load(XacmlApplicationServiceProvider.class);
100         //
101         // Find the guard service application and save for use in all the tests
102         //
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();
108             //
109             // Is it our service?
110             //
111             if (application instanceof GuardPdpApplication) {
112                 //
113                 // Should be the first and only one
114                 //
115                 assertThat(service).isNull();
116                 service = application;
117             }
118             strDump.append(application.applicationName());
119             strDump.append(" supports ");
120             strDump.append(application.supportedPolicyTypes());
121             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
122         }
123         LOGGER.info("{}", strDump);
124         //
125         // Tell it to initialize based on the properties file
126         // we just built for it.
127         //
128         service.initialize(propertiesFile.toPath().getParent(), null);
129         //
130         // Load Decision Requests
131         //
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";
141         em = Persistence
142             .createEntityManagerFactory(SonCoordinationTest.properties.getProperty(persistenceUnit),
143                 properties)
144             .createEntityManager();
145     }
146
147     /**
148      * Clears the database before each test.
149      *
150      */
151     @Before
152     public void startClean() throws Exception {
153         em.getTransaction().begin();
154         em.createQuery("DELETE FROM OperationsHistory").executeUpdate();
155         em.getTransaction().commit();
156     }
157
158     /**
159      * Close the entity manager.
160      */
161     @AfterClass
162     public static void cleanup() throws Exception {
163         if (em != null) {
164             em.close();
165         }
166     }
167
168     /**
169      * Check that decision matches expectation.
170      *
171      * @param expected from the response
172      * @param response received
173      *
174      **/
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);
180         //
181         // Dump it out as Json
182         //
183         LOGGER.info(gson.encode(response));
184     }
185
186     /**
187      * Request a decision and check that it matches expectation.
188      *
189      * @param request to send to Xacml PDP
190      * @param expected from the response
191      *
192      **/
193     public void requestAndCheckDecision(DecisionRequest request, String expected)
194         throws CoderException {
195
196         //
197         // Ask for a decision
198         //
199         Pair<DecisionResponse, Response> decision = service.makeDecision(request, null);
200         //
201         // Check decision
202         //
203         checkDecision(expected, decision.getKey());
204     }
205
206     @Test
207     public void test1() throws CoderException, IOException, XacmlApplicationException {
208         LOGGER.info("**************** Running vPci and vSonh Control Loops ****************");
209         //
210         // Now load the test coordination policy - make sure
211         // the pdp can support it and have it load
212         // into the PDP.
213         //
214         TestUtils.loadPolicies(
215             "src/test/resources/test.policy.guard.coordination.vPciBlocksVsonh.tosca.yaml",
216             service);
217         TestUtils.loadPolicies(
218             "src/test/resources/test.policy.guard.coordination.vSonhBlocksVpci.tosca.yaml",
219             service);
220         //
221         // vSonh doesn't have open action: vPci should get permit
222         //
223         requestAndCheckDecision(requestVpciNode1, PERMIT);
224         //
225         // vPci doesn't have open action: vSonh should get permit
226         //
227         requestAndCheckDecision(requestVsonhNode1, PERMIT);
228         //
229         // Open vSonh on node1
230         //
231         long vsonhId = insertOperationEvent(requestVsonhNode1, "Started");
232         //
233         // Under current coordination policy vPci should get a deny
234         //
235         requestAndCheckDecision(requestVpciNode1, DENY);
236         //
237         // Close vSonh on node1
238         //
239         updateOperationEvent(vsonhId, "Success");
240         //
241         // With vSonh closed on node 1, vPci now should get a permit
242         //
243         requestAndCheckDecision(requestVpciNode1, PERMIT);
244         //
245         // Open vPci on node1
246         //
247         long vpciId = insertOperationEvent(requestVpciNode1, "Started");
248         //
249         // Under current coordination policy vSonh should get a deny
250         //
251         requestAndCheckDecision(requestVsonhNode1, DENY);
252         //
253         // Close cl1 on node1
254         //
255         updateOperationEvent(vpciId, "Failed");
256         //
257         // With vPci closed on node 1, vSonh now should get a permit
258         //
259         requestAndCheckDecision(requestVsonhNode1, PERMIT);
260     }
261
262     @SuppressWarnings("unchecked")
263     private long insertOperationEvent(DecisionRequest request, String outcome) {
264         //
265         // Get the properties
266         //
267         Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
268         //
269         // Add an entry
270         //
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();
284     }
285
286     private void updateOperationEvent(long id, String outcome) {
287
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();
294     }
295
296 }