Merge "Fix for Sonar major issues"
[policy/drools-applications.git] / controlloop / templates / template.demo / src / test / java / org / onap / policy / template / demo / VDNSControlLoopTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
4  * ================================================================================
5  * Copyright (C) 2017 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  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.template.demo;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertFalse;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
28
29 import java.io.IOException;
30 import java.net.URLEncoder;
31 import java.time.Instant;
32 import java.util.HashMap;
33 import java.util.UUID;
34
35 import org.junit.AfterClass;
36 import org.junit.BeforeClass;
37 import org.junit.Test;
38 import org.kie.api.runtime.KieSession;
39 import org.kie.api.runtime.rule.FactHandle;
40 import org.onap.policy.controlloop.ControlLoopEventStatus;
41 import org.onap.policy.controlloop.ControlLoopNotificationType;
42 import org.onap.policy.controlloop.ControlLoopTargetType;
43 import org.onap.policy.controlloop.VirtualControlLoopEvent;
44 import org.onap.policy.controlloop.VirtualControlLoopNotification;
45 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
46 import org.onap.policy.controlloop.policy.TargetType;
47 import org.onap.policy.drools.http.server.HttpServletServer;
48 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
49 import org.onap.policy.drools.system.PolicyEngine;
50 import org.onap.policy.guard.PolicyGuard;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 public class VDNSControlLoopTest {
55
56     private static final Logger logger = LoggerFactory.getLogger(VDNSControlLoopTest.class);
57     
58     private KieSession kieSession;
59     private Util.Pair<ControlLoopPolicy, String> pair;
60     private PolicyEngineJUnitImpl engine;     
61     
62     static {
63         /* Set environment properties */
64         PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666");
65         PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI");
66         PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI");
67         
68         PolicyEngine.manager.setEnvironmentProperty("so.url", "http://localhost:6667");
69         PolicyEngine.manager.setEnvironmentProperty("so.username", "SO");
70         PolicyEngine.manager.setEnvironmentProperty("so.password", "SO");
71     }
72     
73         @BeforeClass
74         public static void setUpSimulator() {
75                 try {
76                         Util.buildAaiSim();
77                         Util.buildSoSim();
78                 } catch (Exception e) {
79                         fail(e.getMessage());
80                 }
81         }
82
83         @AfterClass
84         public static void tearDownSimulator() {
85                 HttpServletServer.factory.destroy();
86         }
87
88     @Test
89     public void successTest() {
90         
91         /*
92          * Start the kie session
93          */
94         try {
95             kieSession = startSession("src/main/resources/ControlLoop_Template_xacml_guard.drl", 
96                         "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml",
97                         "type=operational", 
98                         "CL_vDNS", 
99                         "v2.0");
100         } catch (IOException e) {
101             e.printStackTrace();
102             logger.debug("Could not create kieSession");
103             fail("Could not create kieSession");
104         }
105         
106         /*
107          * Create a thread to continuously fire rules 
108          * until main thread calls halt
109          */      
110         new Thread( new Runnable() {
111             @Override
112             public void run() {
113                 kieSession.fireUntilHalt();
114             }
115           } ).start();
116         
117         /*
118          * Create a unique requestId and a unique trigger source
119          */
120         UUID requestID = UUID.randomUUID();
121         String triggerSourceName = "foobartriggersource36";
122         
123         /*
124          * This will be the object returned from the PolicyEngine
125          */
126         Object obj = null;
127         
128         /* 
129          * Simulate an onset event the policy engine will 
130          * receive from DCAE to kick off processing through
131          * the rules
132          */
133         try {
134             sendOnset(pair.a, requestID, triggerSourceName);
135         } catch (InterruptedException e) {
136             e.printStackTrace();
137             logger.debug("Unable to send onset event");
138             fail("Unable to send onset event");
139         }
140         
141         /*
142          * Pull the object that was sent out and make
143          * sure it is a ControlLoopNoticiation of type active
144          */
145         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
146         assertNotNull(obj);
147         assertTrue(obj instanceof VirtualControlLoopNotification);
148         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.ACTIVE));
149         
150
151         /*
152          * Give the control loop time to acquire a lock
153          */
154         try {
155             Thread.sleep(4000);
156         } catch (InterruptedException e) {
157             e.printStackTrace();
158             logger.debug("An interrupt Exception was thrown");
159             fail("An interrupt Exception was thrown");
160         }
161
162       /*
163       * Give time to finish processing
164       */
165      try {
166          Thread.sleep(10000);
167      } catch (InterruptedException e) {
168          e.printStackTrace();
169          logger.debug("An interrupt Exception was thrown");
170          fail("An interrupt Exception was thrown");
171      }     
172
173             /*
174              * One final check to make sure the lock is released 
175              */
176             assertFalse(PolicyGuard.isLocked(TargetType.VNF, triggerSourceName, requestID));
177
178         /*
179          * This will stop the thread that is firing the rules
180          */
181         kieSession.halt();
182         
183         /*
184          * The only fact in memory should be Params
185          */
186         assertEquals(1, kieSession.getFactCount());
187         
188         /*
189          * Print what's left in memory
190          */
191         dumpFacts(kieSession);
192         
193         /*
194          * Gracefully shut down the kie session
195          */
196         kieSession.dispose();
197     }
198     
199     /**
200      * This method will start a kie session and instantiate 
201      * the Policy Engine.
202      * 
203      * @param droolsTemplate
204      *          the DRL rules file
205      * @param yamlFile
206      *          the yaml file containing the policies
207      * @param policyScope
208      *          scope for policy
209      * @param policyName
210      *          name of the policy
211      * @param policyVersion
212      *          version of the policy          
213      * @return the kieSession to be used to insert facts 
214      * @throws IOException
215      */
216     private KieSession startSession(String droolsTemplate, 
217             String yamlFile, 
218             String policyScope, 
219             String policyName, 
220             String policyVersion) throws IOException {
221         
222         /*
223          * Load policies from yaml
224          */
225         pair = Util.loadYaml(yamlFile);
226         assertNotNull(pair);
227         assertNotNull(pair.a);
228         assertNotNull(pair.a.getControlLoop());
229         assertNotNull(pair.a.getControlLoop().getControlLoopName());
230         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
231         
232         /* 
233          * Construct a kie session
234          */
235         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
236                 pair.a.getControlLoop().getControlLoopName(), 
237                 policyScope, 
238                 policyName, 
239                 policyVersion, 
240                 URLEncoder.encode(pair.b, "UTF-8"));
241         
242         /*
243          * Retrieve the Policy Engine
244          */
245         engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
246         
247         logger.debug("============");
248         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
249         logger.debug("============");
250         
251         return kieSession;
252     }
253
254     /**
255      * This method is used to simulate event messages from DCAE
256      * that start the control loop (onset message).
257      * 
258      * @param policy the controlLoopName comes from the policy 
259      * @param requestID the requestId for this event
260      * @param triggerSourceName 
261      * @throws InterruptedException
262      */
263     protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
264         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
265         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
266         event.requestID = requestID;
267         event.target = "VNF_NAME";
268                 event.target_type = ControlLoopTargetType.VNF;
269         event.closedLoopAlarmStart = Instant.now();
270         event.AAI = new HashMap<>();
271         event.AAI.put("cloud-region.identity-url", "foo");
272         event.AAI.put("vserver.selflink", "bar");
273         event.AAI.put("vserver.is-closed-loop-disabled", "false");
274         event.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
275         event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
276         kieSession.insert(event);
277         Thread.sleep(2000);
278     }
279     
280     /**
281      * This method is used to simulate event messages from DCAE
282      * that end the control loop (abatement message).
283      * 
284      * @param policy the controlLoopName comes from the policy 
285      * @param requestID the requestId for this event
286      * @param triggerSourceName 
287      * @throws InterruptedException
288      */
289     protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
290         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
291         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
292         event.requestID = requestID;
293         event.target = "generic-vnf.vnf-id";
294         event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
295         event.closedLoopAlarmEnd = Instant.now();
296         event.AAI = new HashMap<>();
297         event.AAI.put("cloud-region.identity-url", "foo");
298         event.AAI.put("vserver.selflink", "bar");
299         event.AAI.put("vserver.is-closed-loop-disabled", "false");
300         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
301         event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
302         kieSession.insert(event);
303     }
304     
305     /**
306      * This method will dump all the facts in the working memory.
307      * 
308      * @param kieSession the session containing the facts
309      */
310     public void dumpFacts(KieSession kieSession) {
311         logger.debug("Fact Count: {}", kieSession.getFactCount());
312         for (FactHandle handle : kieSession.getFactHandles()) {
313             logger.debug("FACT: {}", handle);
314         }
315     }
316 }