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