4cd00547189797c7fc7cae95eb71892679413efb
[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.appc.Request;
40 import org.onap.policy.appc.Response;
41 import org.onap.policy.appc.ResponseCode;
42 import org.onap.policy.controlloop.ControlLoopEventStatus;
43 import org.onap.policy.controlloop.ControlLoopNotificationType;
44 import org.onap.policy.controlloop.VirtualControlLoopEvent;
45 import org.onap.policy.controlloop.VirtualControlLoopNotification;
46 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
47 import org.onap.policy.controlloop.policy.TargetType;
48 import org.onap.policy.drools.http.server.HttpServletServer;
49 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
50 import org.onap.policy.guard.PolicyGuard;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 public class VFWControlLoopTest {
55
56     private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.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     }
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         if (kieSession.getFactCount() != 1L) {
333             logger.error("FACT count mismatch: 1 expected but there are {}", kieSession.getFactCount());
334         }
335         
336         /*
337          * Print what's left in memory
338          */
339         dumpFacts(kieSession);
340         
341         /*
342          * Gracefully shut down the kie session
343          */
344         kieSession.dispose();
345     }
346     
347     /**
348      * This method will start a kie session and instantiate 
349      * the Policy Engine.
350      * 
351      * @param droolsTemplate
352      *          the DRL rules file
353      * @param yamlFile
354      *          the yaml file containing the policies
355      * @param policyScope
356      *          scope for policy
357      * @param policyName
358      *          name of the policy
359      * @param policyVersion
360      *          version of the policy          
361      * @return the kieSession to be used to insert facts 
362      * @throws IOException
363      */
364     private KieSession startSession(String droolsTemplate, 
365             String yamlFile, 
366             String policyScope, 
367             String policyName, 
368             String policyVersion) throws IOException {
369         
370         /*
371          * Load policies from yaml
372          */
373         pair = Util.loadYaml(yamlFile);
374         assertNotNull(pair);
375         assertNotNull(pair.a);
376         assertNotNull(pair.a.getControlLoop());
377         assertNotNull(pair.a.getControlLoop().getControlLoopName());
378         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
379         
380         /* 
381          * Construct a kie session
382          */
383         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
384                 pair.a.getControlLoop().getControlLoopName(), 
385                 policyScope, 
386                 policyName, 
387                 policyVersion, 
388                 URLEncoder.encode(pair.b, "UTF-8"));
389         
390         /*
391          * Retrieve the Policy Engine
392          */
393         engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
394         
395         logger.debug("============");
396         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
397         logger.debug("============");
398         
399         return kieSession;
400     }
401
402     /**
403      * This method is used to simulate event messages from DCAE
404      * that start the control loop (onset message).
405      * 
406      * @param policy the controlLoopName comes from the policy 
407      * @param requestID the requestId for this event
408      * @param triggerSourceName 
409      * @throws InterruptedException
410      */
411     protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
412         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
413         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
414         event.requestID = requestID;
415         event.target = "generic-vnf.vnf-id";
416         event.closedLoopAlarmStart = Instant.now();
417         event.AAI = new HashMap<>();
418         event.AAI.put("cloud-region.identity-url", "foo");
419         event.AAI.put("vserver.selflink", "bar");
420         event.AAI.put("vserver.is-closed-loop-disabled", "false");
421         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
422         event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
423         kieSession.insert(event);
424         Thread.sleep(2000);
425     }
426     
427     /**
428      * This method is used to simulate event messages from DCAE
429      * that end the control loop (abatement message).
430      * 
431      * @param policy the controlLoopName comes from the policy 
432      * @param requestID the requestId for this event
433      * @param triggerSourceName 
434      * @throws InterruptedException
435      */
436     protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
437         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
438         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
439         event.requestID = requestID;
440         event.target = "generic-vnf.vnf-id";
441         event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
442         event.closedLoopAlarmEnd = Instant.now();
443         event.AAI = new HashMap<>();
444         event.AAI.put("cloud-region.identity-url", "foo");
445         event.AAI.put("vserver.selflink", "bar");
446         event.AAI.put("vserver.is-closed-loop-disabled", "false");
447         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
448         event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
449         kieSession.insert(event);
450     }
451     
452     /**
453      * This method will dump all the facts in the working memory.
454      * 
455      * @param kieSession the session containing the facts
456      */
457     public void dumpFacts(KieSession kieSession) {
458         logger.debug("Fact Count: {}", kieSession.getFactCount());
459         for (FactHandle handle : kieSession.getFactHandles()) {
460             logger.debug("FACT: {}", handle);
461         }
462     }
463 }