b350570ba4247f870968cdfae7bcea40e38c8b07
[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.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         Util.setAAIProps();
65         Util.setSOProps();
66     }
67     
68         @BeforeClass
69         public static void setUpSimulator() {
70                 try {
71                         Util.buildAaiSim();
72                         Util.buildSoSim();
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         
183         /*
184          * Print what's left in memory
185          */
186         dumpFacts(kieSession);
187         
188         /*
189          * Gracefully shut down the kie session
190          */
191         kieSession.dispose();
192     }
193     
194     /**
195      * This method will start a kie session and instantiate 
196      * the Policy Engine.
197      * 
198      * @param droolsTemplate
199      *          the DRL rules file
200      * @param yamlFile
201      *          the yaml file containing the policies
202      * @param policyScope
203      *          scope for policy
204      * @param policyName
205      *          name of the policy
206      * @param policyVersion
207      *          version of the policy          
208      * @return the kieSession to be used to insert facts 
209      * @throws IOException
210      */
211     private KieSession startSession(String droolsTemplate, 
212             String yamlFile, 
213             String policyScope, 
214             String policyName, 
215             String policyVersion) throws IOException {
216         
217         /*
218          * Load policies from yaml
219          */
220         pair = Util.loadYaml(yamlFile);
221         assertNotNull(pair);
222         assertNotNull(pair.a);
223         assertNotNull(pair.a.getControlLoop());
224         assertNotNull(pair.a.getControlLoop().getControlLoopName());
225         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
226         
227         /* 
228          * Construct a kie session
229          */
230         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
231                 pair.a.getControlLoop().getControlLoopName(), 
232                 policyScope, 
233                 policyName, 
234                 policyVersion, 
235                 URLEncoder.encode(pair.b, "UTF-8"));
236         
237         /*
238          * Retrieve the Policy Engine
239          */
240         engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
241         
242         logger.debug("============");
243         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
244         logger.debug("============");
245         
246         return kieSession;
247     }
248
249     /**
250      * This method is used to simulate event messages from DCAE
251      * that start the control loop (onset message).
252      * 
253      * @param policy the controlLoopName comes from the policy 
254      * @param requestID the requestId for this event
255      * @param triggerSourceName 
256      * @throws InterruptedException
257      */
258     protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
259         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
260         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
261         event.requestID = requestID;
262         event.target = "VNF_NAME";
263                 event.target_type = ControlLoopTargetType.VNF;
264         event.closedLoopAlarmStart = Instant.now();
265         event.AAI = new HashMap<>();
266         event.AAI.put("cloud-region.identity-url", "foo");
267         event.AAI.put("vserver.selflink", "bar");
268         event.AAI.put("vserver.is-closed-loop-disabled", "false");
269         event.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
270         event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
271         kieSession.insert(event);
272         Thread.sleep(2000);
273     }
274     
275     /**
276      * This method is used to simulate event messages from DCAE
277      * that end the control loop (abatement message).
278      * 
279      * @param policy the controlLoopName comes from the policy 
280      * @param requestID the requestId for this event
281      * @param triggerSourceName 
282      * @throws InterruptedException
283      */
284     protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
285         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
286         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
287         event.requestID = requestID;
288         event.target = "generic-vnf.vnf-id";
289         event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
290         event.closedLoopAlarmEnd = Instant.now();
291         event.AAI = new HashMap<>();
292         event.AAI.put("cloud-region.identity-url", "foo");
293         event.AAI.put("vserver.selflink", "bar");
294         event.AAI.put("vserver.is-closed-loop-disabled", "false");
295         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
296         event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
297         kieSession.insert(event);
298     }
299     
300     /**
301      * This method will dump all the facts in the working memory.
302      * 
303      * @param kieSession the session containing the facts
304      */
305     public void dumpFacts(KieSession kieSession) {
306         logger.debug("Fact Count: {}", kieSession.getFactCount());
307         for (FactHandle handle : kieSession.getFactHandles()) {
308             logger.debug("FACT: {}", handle);
309         }
310     }
311 }