d43537b80610832bcfc8bae6602fda9b3cce6ef7
[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.appclcm.LCMRequest;
37 import org.onap.policy.appclcm.LCMRequestWrapper;
38 import org.onap.policy.appclcm.LCMResponse;
39 import org.onap.policy.appclcm.LCMResponseWrapper;
40 import org.onap.policy.controlloop.ControlLoopEventStatus;
41 import org.onap.policy.controlloop.ControlLoopNotificationType;
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 VCPEControlLoopTest {
53
54     private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.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.setGuardProps();
64     }
65     
66     @BeforeClass
67     public static void setUpSimulator() {
68         try {
69             Util.buildAaiSim();
70             Util.buildGuardSim();
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_vCPE.yaml",
90                         "service=ServiceTest;resource=ResourceTest;type=operational", 
91                         "CL_vCPE", 
92                         "org.onap.closed_loop.ServiceTest: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 Restart!!!!!!");
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("PERMIT")) {
196             
197             /* 
198              * A notification should be sent out of the Policy
199              * Engine at this point, it will be of type operation
200              */
201             obj = engine.subscribe("UEB", "POLICY-CL-MGT");
202             assertNotNull(obj);
203             logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
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-LCM-READ");
223             assertNotNull(obj);
224             
225             /*
226              * The request should be of type LCMRequestWrapper
227              * and the subrequestid should be 1
228              */
229             assertTrue(obj instanceof LCMRequestWrapper);
230             LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
231             LCMRequest appcRequest = dmaapRequest.getBody();
232             assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
233             
234             logger.debug("\n============ APPC received the request!!! ===========\n");
235
236             /*
237              * Give some time for processing
238              */
239             try {
240                 Thread.sleep(1000);
241             } catch (InterruptedException e) {
242                 e.printStackTrace();
243                 logger.debug("An interrupt Exception was thrown");
244                 fail("An interrupt Exception was thrown");
245             }
246             
247             /*
248              * Simulate a success response from APPC and insert
249              * the response into the working memory
250              */
251             LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
252             LCMResponse appcResponse = new LCMResponse(appcRequest);
253             appcResponse.getStatus().setCode(400);
254             appcResponse.getStatus().setMessage("AppC success");
255             dmaapResponse.setBody(appcResponse);
256             kieSession.insert(dmaapResponse);
257             
258             /* 
259              * Give time for processing
260              */
261             try {
262                 Thread.sleep(10000);
263             } catch (InterruptedException e) {
264                 e.printStackTrace();
265                 logger.debug("An interrupt Exception was thrown");
266                 fail("An interrupt Exception was thrown");
267             }
268             
269             /*
270              * Make sure the next notification is delivered
271              */
272             obj = engine.subscribe("UEB", "POLICY-CL-MGT");
273             assertNotNull(obj);
274             logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
275             
276             /*
277              * The ControlLoopNotification should be
278              * an OPERATION_SUCCESS
279              */
280             assertTrue(obj instanceof VirtualControlLoopNotification);
281             assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION_SUCCESS));
282             
283             /* 
284              * Now simulate the abatement sent from DCAE
285              */
286             try {
287                 sendAbatement(pair.a, requestID, triggerSourceName);
288             } catch (InterruptedException e1) {
289                 e1.printStackTrace();
290                 logger.debug("Abatement could not be sent");
291                 fail("Abatement could not be sent");
292             }
293             
294             /*
295              * Give time to finish processing
296              */
297             try {
298                 Thread.sleep(20000);
299             } catch (InterruptedException e) {
300                 e.printStackTrace();
301                 logger.debug("An interrupt Exception was thrown");
302                 fail("An interrupt Exception was thrown");
303             }     
304             
305             /*
306              * This should be the final notification from the Policy Engine
307              */
308             obj = engine.subscribe("UEB", "POLICY-CL-MGT");
309             assertNotNull(obj);
310             logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
311             
312             /*
313              * The ControlLoopNotification should be of type FINAL_SUCCESS
314              */
315             assertTrue(obj instanceof VirtualControlLoopNotification);
316             assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.FINAL_SUCCESS));
317             
318             /*
319              * One final check to make sure the lock is released 
320              */
321             assertFalse(PolicyGuard.isLocked(TargetType.VNF, triggerSourceName, requestID));
322         }
323         else {
324             fail("Operation Denied by Guard");
325         }
326         
327         /*
328          * This will stop the thread that is firing the rules
329          */
330         kieSession.halt();
331         
332         /*
333          * The only fact in memory should be Params
334          */
335         //assertEquals(1, kieSession.getFactCount());
336         if (kieSession.getFactCount() != 1L) {
337             logger.error("FACT count mismatch: 1 expected but there are {}", kieSession.getFactCount());
338         }
339         
340         /*
341          * Print what's left in memory
342          */
343         dumpFacts(kieSession);
344         
345         /*
346          * Gracefully shut down the kie session
347          */
348         kieSession.dispose();
349     }
350
351     /**
352      * This method will start a kie session and instantiate 
353      * the Policy Engine.
354      * 
355      * @param droolsTemplate
356      *          the DRL rules file
357      * @param yamlFile
358      *          the yaml file containing the policies
359      * @param policyScope
360      *          scope for policy
361      * @param policyName
362      *          name of the policy
363      * @param policyVersion
364      *          version of the policy          
365      * @return the kieSession to be used to insert facts 
366      * @throws IOException
367      */
368     private KieSession startSession(String droolsTemplate, 
369             String yamlFile, 
370             String policyScope, 
371             String policyName, 
372             String policyVersion) throws IOException {
373         
374         /*
375          * Load policies from yaml
376          */
377         pair = Util.loadYaml(yamlFile);
378         assertNotNull(pair);
379         assertNotNull(pair.a);
380         assertNotNull(pair.a.getControlLoop());
381         assertNotNull(pair.a.getControlLoop().getControlLoopName());
382         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
383         
384         /* 
385          * Construct a kie session
386          */
387         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
388                 pair.a.getControlLoop().getControlLoopName(), 
389                 policyScope, 
390                 policyName, 
391                 policyVersion, 
392                 URLEncoder.encode(pair.b, "UTF-8"));
393         
394         /*
395          * Retrieve the Policy Engine
396          */
397         engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
398         
399         logger.debug("============");
400         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
401         logger.debug("============");
402         
403         return kieSession;
404     }
405     
406     /**
407      * This method is used to simulate event messages from DCAE
408      * that start the control loop (onset message).
409      * 
410      * @param policy the controlLoopName comes from the policy 
411      * @param requestID the requestId for this event
412      * @param triggerSourceName 
413      * @throws InterruptedException
414      */
415     protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
416         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
417         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
418         event.requestID = requestID;
419         event.target = "generic-vnf.vnf-id";
420         event.closedLoopAlarmStart = Instant.now();
421         event.AAI = new HashMap<>();
422         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfId");
423         event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
424         kieSession.insert(event);
425         Thread.sleep(2000);
426     }
427     
428     /**
429      * This method is used to simulate event messages from DCAE
430      * that end the control loop (abatement message).
431      * 
432      * @param policy the controlLoopName comes from the policy 
433      * @param requestID the requestId for this event
434      * @param triggerSourceName 
435      * @throws InterruptedException
436      */
437     protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
438         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
439         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
440         event.requestID = requestID;
441         event.target = "generic-vnf.vnf-id";
442         event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
443         event.closedLoopAlarmEnd = Instant.now();
444         event.AAI = new HashMap<>();
445         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfId");
446         event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
447         kieSession.insert(event);
448     }
449     
450     /**
451      * This method will dump all the facts in the working memory.
452      * 
453      * @param kieSession the session containing the facts
454      */
455     public void dumpFacts(KieSession kieSession) {
456         logger.debug("Fact Count: {}", kieSession.getFactCount());
457         for (FactHandle handle : kieSession.getFactHandles()) {
458             logger.debug("FACT: {}", handle);
459         }
460     }
461 }