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