Merge "Add Control Loop Coordination policy."
[policy/xacml-pdp.git] / applications / guard / src / test / java / org / onap / policy / xacml / pdp / application / guard / CoordinationTest.java
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.guard;
24
25 import static org.assertj.core.api.Assertions.assertThat;
26
27 import java.io.File;
28 import java.io.IOException;
29 import java.sql.Date;
30 import java.time.Instant;
31 import java.util.Iterator;
32 import java.util.Map;
33 import java.util.Properties;
34 import java.util.ServiceLoader;
35 import java.util.UUID;
36
37 import javax.persistence.EntityManager;
38 import javax.persistence.Persistence;
39
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.models.decisions.concepts.DecisionRequest;
52 import org.onap.policy.models.decisions.concepts.DecisionResponse;
53 import org.onap.policy.pdp.xacml.application.common.TestUtils;
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.application.common.operationshistory.Dbao;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
63 public class CoordinationTest {
64
65     private static final Logger LOGGER = LoggerFactory.getLogger(CoordinationTest.class);
66     private static Properties properties = new Properties();
67     private static File propertiesFile;
68     private static XacmlApplicationServiceProvider service;
69     private static DecisionRequest requestCl1Node1;
70     private static DecisionRequest requestCl1Node2;
71     private static DecisionRequest requestCl2Node1;
72     private static DecisionRequest requestCl2Node2;
73     private static StandardCoder gson = new StandardCoder();
74     private static EntityManager em;
75     private static final String DENY = "Deny";
76     private static final String PERMIT = "Permit";
77     private static final String OPEN = "Success";
78     private static final String CLOSE = "Closed";
79
80
81     @ClassRule
82     public static final TemporaryFolder policyFolder = new TemporaryFolder();
83
84     /**
85      * Copies the xacml.properties and policies files into
86      * temporary folder and loads the service provider saving
87      * instance of provider off for other tests to use.
88      */
89     @BeforeClass
90     public static void setup() throws Exception {
91         LOGGER.info("Setting up class");
92         //
93         // Setup our temporary folder
94         //
95         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
96         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
97                 properties, myCreator);
98         //
99         // Load service
100         //
101         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
102                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
103         //
104         // Find the guard service application and save for use in all the tests
105         //
106         StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
107         Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
108         while (iterator.hasNext()) {
109             XacmlApplicationServiceProvider application = iterator.next();
110             //
111             // Is it our service?
112             //
113             if (application instanceof GuardPdpApplication) {
114                 //
115                 // Should be the first and only one
116                 //
117                 assertThat(service).isNull();
118                 service = application;
119             }
120             strDump.append(application.applicationName());
121             strDump.append(" supports ");
122             strDump.append(application.supportedPolicyTypes());
123             strDump.append(System.lineSeparator());
124         }
125         LOGGER.info("{}", strDump);
126         //
127         // Tell it to initialize based on the properties file
128         // we just built for it.
129         //
130         service.initialize(propertiesFile.toPath().getParent());
131         //
132         // Load Decision Requests
133         //
134         requestCl1Node1 = gson.decode(
135                 TextFileUtils.getTextFileAsString(
136                     "src/test/resources/requests/coordination.cl.1.node.1.json"),
137                     DecisionRequest.class);
138         requestCl2Node1 = gson.decode(
139                 TextFileUtils.getTextFileAsString(
140                     "src/test/resources/requests/coordination.cl.2.node.1.json"),
141                     DecisionRequest.class);
142         requestCl1Node2 = gson.decode(
143                 TextFileUtils.getTextFileAsString(
144                     "src/test/resources/requests/coordination.cl.1.node.2.json"),
145                     DecisionRequest.class);
146         requestCl2Node2 = gson.decode(
147                 TextFileUtils.getTextFileAsString(
148                     "src/test/resources/requests/coordination.cl.2.node.2.json"),
149                     DecisionRequest.class);
150         //
151         // Create EntityManager for manipulating DB
152         //
153         String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
154         em = Persistence.createEntityManagerFactory(
155                 CoordinationTest.properties.getProperty(persistenceUnit), properties)
156                 .createEntityManager();
157     }
158
159     /**
160      * Clears the database before each test.
161      *
162      */
163     @Before
164     public void startClean() throws Exception {
165         em.getTransaction().begin();
166         em.createQuery("DELETE FROM Dbao").executeUpdate();
167         em.getTransaction().commit();
168     }
169
170     /**
171      * Check that decision matches expectation.
172      *
173      * @param expected from the response
174      * @param response received
175      *
176      **/
177     public void checkDecision(String expected, DecisionResponse response) throws CoderException {
178         LOGGER.info("Looking for {} Decision", expected);
179         assertThat(response).isNotNull();
180         assertThat(response.getStatus()).isNotNull();
181         assertThat(response.getStatus()).isEqualTo(expected);
182         //
183         // Dump it out as Json
184         //
185         LOGGER.info(gson.encode(response));
186     }
187
188     /**
189      * Request a decision and check that it matches expectation.
190      *
191      * @param request to send to Xacml PDP
192      * @param expected from the response
193      *
194      **/
195     public void requestAndCheckDecision(DecisionRequest request, String expected) throws CoderException {
196         //
197         // Ask for a decision
198         //
199         DecisionResponse response = service.makeDecision(request);
200         //
201         // Check decision
202         //
203         checkDecision(expected, response);
204     }
205
206     @Test
207     public void test1() throws CoderException, IOException, XacmlApplicationException {
208         LOGGER.info("**************** Running test1 ****************");
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("src/test/resources/test.policy.guard.coordination.firstBlocksSecond.tosca.yaml",
215                 service);
216         //
217         // cl1 doesn't have open action: cl2 should get permit
218         //
219         requestAndCheckDecision(requestCl2Node1, PERMIT);
220         //
221         // Open cl2 on node1
222         //
223         insertOperationEvent(requestCl2Node1, OPEN);
224         //
225         // Under current coordination policy cl1 always can go
226         //
227         requestAndCheckDecision(requestCl1Node1, PERMIT);
228         //
229         // Open cl1 on node1
230         //
231         insertOperationEvent(requestCl1Node1, OPEN);
232         //
233         // Close cl2 on node1
234         //
235         insertOperationEvent(requestCl2Node1, CLOSE);
236         //
237         // Try cl2 again, cl1 has open action on node1: should get deny
238         //
239         requestAndCheckDecision(requestCl2Node1, DENY);
240         //
241         // Close cl1 on node1
242         //
243         insertOperationEvent(requestCl1Node1, CLOSE);
244         //
245         // Under current coordination policy cl1 always can go
246         //
247         requestAndCheckDecision(requestCl1Node1, PERMIT);
248         //
249         // Open cl1 on node1
250         //
251         insertOperationEvent(requestCl1Node1, OPEN);
252         //
253         // Try cl2 on node2, cl1 only open on node1: should get permit
254         //
255         requestAndCheckDecision(requestCl2Node2, PERMIT);
256         //
257         // Open cl2 on node2
258         //
259         insertOperationEvent(requestCl2Node2, OPEN);
260         //
261         // Try cl2 on node1, cl1 open on node1: should get DENY
262         //
263         requestAndCheckDecision(requestCl2Node1, DENY);
264     }
265
266     @SuppressWarnings("unchecked")
267     private void insertOperationEvent(DecisionRequest request, String outcome) {
268         //
269         // Get the properties
270         //
271         Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
272         //
273         // Add an entry
274         //
275         Dbao newEntry = new Dbao();
276         newEntry.setActor(properties.get("actor").toString());
277         newEntry.setOperation(properties.get("recipe").toString());
278         newEntry.setClosedLoopName(properties.get("clname").toString());
279         newEntry.setOutcome(outcome);
280         newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
281         newEntry.setEndtime(Date.from(Instant.now()));
282         newEntry.setRequestId(UUID.randomUUID().toString());
283         newEntry.setTarget(properties.get("target").toString());
284         em.getTransaction().begin();
285         em.persist(newEntry);
286         em.getTransaction().commit();
287     }
288
289     /**
290      * Close the entity manager.
291      */
292     @AfterClass
293     public static void cleanup() throws Exception {
294         if (em != null) {
295             em.close();
296         }
297     }
298 }