453354dba61c79c86e71d67f35237a124b18cdc3
[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.*;
24
25 import java.io.IOException;
26 import java.net.URLEncoder;
27 import java.time.Instant;
28 import java.util.HashMap;
29 import java.util.UUID;
30
31 import org.junit.AfterClass;
32 import org.junit.BeforeClass;
33 import org.junit.Test;
34 import org.kie.api.runtime.KieSession;
35 import org.kie.api.runtime.rule.FactHandle;
36 import org.onap.policy.appc.Request;
37 import org.onap.policy.appc.Response;
38 import org.onap.policy.appc.ResponseCode;
39 import org.onap.policy.controlloop.ControlLoopEventStatus;
40 import org.onap.policy.controlloop.ControlLoopNotificationType;
41 import org.onap.policy.controlloop.VirtualControlLoopEvent;
42 import org.onap.policy.controlloop.VirtualControlLoopNotification;
43 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
44 import org.onap.policy.controlloop.policy.TargetType;
45 import org.onap.policy.drools.http.server.HttpServletServer;
46 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
47 import org.onap.policy.drools.system.PolicyEngine;
48 import org.onap.policy.guard.PolicyGuard;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 public class VFWControlLoopTest {
53
54     private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.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         PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666");
63         PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI");
64         PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI");
65     }
66     
67     @BeforeClass
68     public static void setUpSimulator() {
69         try {
70             Util.buildAaiSim();
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_vFW.yaml",
90                         "service=ServiceDemo;resource=Res1Demo;type=operational", 
91                         "CL_vFW", 
92                         "org.onap.closed_loop.ServiceDemo:VNFS:1.0.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 to DMAAP 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          * Give the control loop time to acquire a lock
145          */
146         try {
147             Thread.sleep(4000);
148         } catch (InterruptedException e) {
149             e.printStackTrace();
150             logger.debug("An interrupt Exception was thrown");
151             fail("An interrupt Exception was thrown");
152         }
153         
154         /*
155          * The fact should be ready to query guard now to see 
156          * if a ModifyConfig recipe is allowed
157          */
158         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
159         assertNotNull(obj);
160         logger.debug("\n\n####################### GOING TO QUERY GUARD about ModifyConfig!!!!!!");
161         logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
162         
163         /*
164          * Make sure the object is an instance of a ControlLoopNotification
165          * and is of type operation
166          */
167         assertTrue(obj instanceof VirtualControlLoopNotification);
168         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
169     
170         try {
171             Thread.sleep(4000);
172         } catch (InterruptedException e) {
173             e.printStackTrace();
174             logger.debug("An interrupt Exception was thrown");
175             fail("An interrupt Exception was thrown");
176         }
177         
178         /*
179          * The guard response should be received at this point
180          */
181         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
182         assertNotNull(obj);
183         logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
184         
185         /*
186          * The object should be a ControlLoopNotification with type operation
187          */
188         assertTrue(obj instanceof VirtualControlLoopNotification);
189         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
190         
191         /*
192          * See if Guard permits this action, if it does 
193          * not then the test should fail
194          */
195         if (((VirtualControlLoopNotification)obj).message.contains("Guard result: Permit")) {
196             
197             /*
198              * Obtain the ControlLoopNoticiation, it should be of type operation
199              */
200             obj = engine.subscribe("UEB", "POLICY-CL-MGT");
201             assertNotNull(obj);
202             logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
203             
204             /* 
205              * A notification should be sent out of the Policy
206              * Engine at this point, it will be of type operation
207              */
208             assertTrue(obj instanceof VirtualControlLoopNotification);
209             assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
210             
211             try {
212                 Thread.sleep(1000);
213             } catch (InterruptedException e) {
214                 e.printStackTrace();
215                 logger.debug("An interrupt Exception was thrown");
216                 fail("An interrupt Exception was thrown");
217             }
218             
219             /*
220              * Obtain the request sent from the Policy Engine
221              */
222             obj = engine.subscribe("UEB", "APPC-CL");
223             assertNotNull(obj);
224             
225             /*
226              * The request should be of type Request 
227              * and the subrequestid should be 1
228              */
229             assertTrue(obj instanceof Request);
230             assertTrue(((Request)obj).getCommonHeader().SubRequestID.equals("1"));
231             
232             logger.debug("\n============ APPC received the request!!! ===========\n");
233
234             /*
235              * Give some time for processing
236              */
237             try {
238                 Thread.sleep(1000);
239             } catch (InterruptedException e) {
240                 e.printStackTrace();
241                 logger.debug("An interrupt Exception was thrown");
242                 fail("An interrupt Exception was thrown");
243             }
244             
245             /*
246              * Simulate a success response from APPC and insert
247              * the response into the working memory
248              */
249             Response appcResponse = new Response((Request)obj);
250             appcResponse.getStatus().Code = ResponseCode.SUCCESS.getValue();
251             appcResponse.getStatus().Value = "SUCCESS";
252             kieSession.insert(appcResponse);
253             
254             /* 
255              * Give time for processing
256              */
257             try {
258                 Thread.sleep(4000);
259             } catch (InterruptedException e) {
260                 e.printStackTrace();
261                 logger.debug("An interrupt Exception was thrown");
262                 fail("An interrupt Exception was thrown");
263             }
264             
265             /*
266              * Make sure the next notification is delivered
267              */
268             obj = engine.subscribe("UEB", "POLICY-CL-MGT");
269             assertNotNull(obj);
270             logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
271             
272             /*
273              * The ControlLoopNotification should be
274              * an OPERATION_SUCCESS
275              */
276             assertTrue(obj instanceof VirtualControlLoopNotification);
277             assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION_SUCCESS));
278             
279             /* 
280              * Now simulate the abatement sent from DCAE
281              */
282             try {
283                 sendAbatement(pair.a, requestID, triggerSourceName);
284             } catch (InterruptedException e1) {
285                 e1.printStackTrace();
286                 logger.debug("Abatement could not be sent");
287                 fail("Abatement could not be sent");
288             }
289             
290             /*
291              * Give time to finish processing
292              */
293             try {
294                 Thread.sleep(20000);
295             } catch (InterruptedException e) {
296                 e.printStackTrace();
297                 logger.debug("An interrupt Exception was thrown");
298                 fail("An interrupt Exception was thrown");
299             }     
300             
301             /*
302              * This should be the final notification from the Policy Engine
303              */
304             obj = engine.subscribe("UEB", "POLICY-CL-MGT");
305             assertNotNull(obj);
306             logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
307             
308             /*
309              * The ControlLoopNotification should be of type FINAL_SUCCESS
310              */
311             assertTrue(obj instanceof VirtualControlLoopNotification);
312             assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.FINAL_SUCCESS));
313             
314             /*
315              * One final check to make sure the lock is released 
316              */
317             assertFalse(PolicyGuard.isLocked(TargetType.VNF, triggerSourceName, requestID));
318         }
319         else {
320             fail("Operation Denied by Guard");
321         }
322         
323         /*
324          * This will stop the thread that is firing the rules
325          */
326         kieSession.halt();
327         
328         /*
329          * The only fact in memory should be Params
330          */
331         assertEquals(1, kieSession.getFactCount());
332         
333         /*
334          * Print what's left in memory
335          */
336         dumpFacts(kieSession);
337         
338         /*
339          * Gracefully shut down the kie session
340          */
341         kieSession.dispose();
342     }
343     
344     /**
345      * This method will start a kie session and instantiate 
346      * the Policy Engine.
347      * 
348      * @param droolsTemplate
349      *          the DRL rules file
350      * @param yamlFile
351      *          the yaml file containing the policies
352      * @param policyScope
353      *          scope for policy
354      * @param policyName
355      *          name of the policy
356      * @param policyVersion
357      *          version of the policy          
358      * @return the kieSession to be used to insert facts 
359      * @throws IOException
360      */
361     private KieSession startSession(String droolsTemplate, 
362             String yamlFile, 
363             String policyScope, 
364             String policyName, 
365             String policyVersion) throws IOException {
366         
367         /*
368          * Load policies from yaml
369          */
370         pair = Util.loadYaml(yamlFile);
371         assertNotNull(pair);
372         assertNotNull(pair.a);
373         assertNotNull(pair.a.getControlLoop());
374         assertNotNull(pair.a.getControlLoop().getControlLoopName());
375         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
376         
377         /* 
378          * Construct a kie session
379          */
380         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
381                 pair.a.getControlLoop().getControlLoopName(), 
382                 policyScope, 
383                 policyName, 
384                 policyVersion, 
385                 URLEncoder.encode(pair.b, "UTF-8"));
386         
387         /*
388          * Retrieve the Policy Engine
389          */
390         engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
391         
392         logger.debug("============");
393         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
394         logger.debug("============");
395         
396         return kieSession;
397     }
398
399     /**
400      * This method is used to simulate event messages from DCAE
401      * that start the control loop (onset message).
402      * 
403      * @param policy the controlLoopName comes from the policy 
404      * @param requestID the requestId for this event
405      * @param triggerSourceName 
406      * @throws InterruptedException
407      */
408     protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
409         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
410         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
411         event.requestID = requestID;
412         event.target = "generic-vnf.vnf-id";
413         event.closedLoopAlarmStart = Instant.now();
414         event.AAI = new HashMap<>();
415         event.AAI.put("cloud-region.identity-url", "foo");
416         event.AAI.put("vserver.selflink", "bar");
417         event.AAI.put("vserver.is-closed-loop-disabled", "false");
418         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
419         event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
420         kieSession.insert(event);
421         Thread.sleep(2000);
422     }
423     
424     /**
425      * This method is used to simulate event messages from DCAE
426      * that end the control loop (abatement message).
427      * 
428      * @param policy the controlLoopName comes from the policy 
429      * @param requestID the requestId for this event
430      * @param triggerSourceName 
431      * @throws InterruptedException
432      */
433     protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
434         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
435         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
436         event.requestID = requestID;
437         event.target = "generic-vnf.vnf-id";
438         event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
439         event.closedLoopAlarmEnd = Instant.now();
440         event.AAI = new HashMap<>();
441         event.AAI.put("cloud-region.identity-url", "foo");
442         event.AAI.put("vserver.selflink", "bar");
443         event.AAI.put("vserver.is-closed-loop-disabled", "false");
444         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
445         event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
446         kieSession.insert(event);
447     }
448     
449     /**
450      * This method will dump all the facts in the working memory.
451      * 
452      * @param kieSession the session containing the facts
453      */
454     public void dumpFacts(KieSession kieSession) {
455         logger.debug("Fact Count: {}", kieSession.getFactCount());
456         for (FactHandle handle : kieSession.getFactHandles()) {
457             logger.debug("FACT: {}", handle);
458         }
459     }
460 }