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