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