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