182e39828233adf950944bdda2b8801594ad0fda
[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.Test;
32 import org.kie.api.runtime.KieSession;
33 import org.kie.api.runtime.rule.FactHandle;
34 import org.onap.policy.appclcm.LCMRequest;
35 import org.onap.policy.appclcm.LCMRequestWrapper;
36 import org.onap.policy.appclcm.LCMResponse;
37 import org.onap.policy.appclcm.LCMResponseWrapper;
38 import org.onap.policy.controlloop.ControlLoopEventStatus;
39 import org.onap.policy.controlloop.ControlLoopNotificationType;
40 import org.onap.policy.controlloop.VirtualControlLoopEvent;
41 import org.onap.policy.controlloop.VirtualControlLoopNotification;
42 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
43 import org.onap.policy.controlloop.policy.TargetType;
44 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
45 import org.onap.policy.guard.PolicyGuard;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class VCPEControlLoopTest {
50
51     private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class);
52     
53     private KieSession kieSession;
54     private Util.Pair<ControlLoopPolicy, String> pair;
55     private PolicyEngineJUnitImpl engine;        
56     
57     @Test
58     public void successTest() {
59         
60         /*
61          * Start the kie session
62          */
63         try {
64             kieSession = startSession("src/main/resources/ControlLoop_Template_xacml_guard.drl", 
65                         "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
66                         "service=ServiceTest;resource=ResourceTest;type=operational", 
67                         "CL_vCPE", 
68                         "org.onap.closed_loop.ServiceTest:VNFS:1.0.0");
69         } catch (IOException e) {
70             e.printStackTrace();
71             logger.debug("Could not create kieSession");
72             fail("Could not create kieSession");
73         }
74         
75         /*
76          * Create a thread to continuously fire rules 
77          * until main thread calls halt
78          */      
79         new Thread( new Runnable() {
80             @Override
81             public void run() {
82                 kieSession.fireUntilHalt();
83             }
84           } ).start();
85         
86         /*
87          * Create a unique requestId and a unique trigger source
88          */
89         UUID requestID = UUID.randomUUID();
90         String triggerSourceName = "foobartriggersource36";
91         
92         /*
93          * This will be the object returned from the PolicyEngine
94          */
95         Object obj = null;
96         
97         /* 
98          * Simulate an onset event the policy engine will 
99          * receive from DCAE to kick off processing through
100          * the rules.
101          */
102         try {
103             sendOnset(pair.a, requestID, triggerSourceName);
104         } catch (InterruptedException e) {
105             e.printStackTrace();
106             logger.debug("Unable to send onset event");
107             fail("Unable to send onset event");
108         }
109         
110         /*
111          * Pull the object that was sent out to DMAAP and make
112          * sure it is a ControlLoopNoticiation of type active
113          */
114         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
115         assertNotNull(obj);
116         assertTrue(obj instanceof VirtualControlLoopNotification);
117         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.ACTIVE));
118         
119         /*
120          * Give the control loop time to acquire a lock
121          */
122         try {
123             Thread.sleep(4000);
124         } catch (InterruptedException e) {
125             e.printStackTrace();
126             logger.debug("An interrupt Exception was thrown");
127             fail("An interrupt Exception was thrown");
128         }
129         
130         /*
131          * The fact should be ready to query guard now to see 
132          * if a ModifyConfig recipe is allowed
133          */
134         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
135         assertNotNull(obj);
136         logger.debug("\n\n####################### GOING TO QUERY GUARD about Restart!!!!!!");
137         logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
138         
139         /*
140          * Make sure the object is an instance of a ControlLoopNotification
141          * and is of type operation
142          */
143         assertTrue(obj instanceof VirtualControlLoopNotification);
144         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
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 guard response should be received at this point
156          */
157         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
158         assertNotNull(obj);
159         logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
160         
161         /*
162          * The object should be a ControlLoopNotification with type operation
163          */
164         assertTrue(obj instanceof VirtualControlLoopNotification);
165         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
166         
167         /*
168          * See if Guard permits this action, if it does 
169          * not then the test should fail
170          */
171         if (((VirtualControlLoopNotification)obj).message.contains("Guard result: Permit")) {
172             
173             /* 
174              * A notification should be sent out of the Policy
175              * Engine at this point, it will be of type operation
176              */
177             obj = engine.subscribe("UEB", "POLICY-CL-MGT");
178             assertNotNull(obj);
179             logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
180             
181             /* A notification should be sent out of the Policy
182              * Engine at this point, it will be of type operation
183              */
184             assertTrue(obj instanceof VirtualControlLoopNotification);
185             assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
186             
187             try {
188                 Thread.sleep(1000);
189             } catch (InterruptedException e) {
190                 e.printStackTrace();
191                 logger.debug("An interrupt Exception was thrown");
192                 fail("An interrupt Exception was thrown");
193             }
194             
195             /*
196              * Obtain the request sent from the Policy Engine
197              */
198             obj = engine.subscribe("UEB", "APPC-CL");
199             assertNotNull(obj);
200             
201             /*
202              * The request should be of type LCMRequestWrapper
203              * and the subrequestid should be 1
204              */
205             assertTrue(obj instanceof LCMRequestWrapper);
206             LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
207             LCMRequest appcRequest = dmaapRequest.getBody();
208             assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
209             
210             logger.debug("\n============ APPC received the request!!! ===========\n");
211
212             /*
213              * Give some time for processing
214              */
215             try {
216                 Thread.sleep(1000);
217             } catch (InterruptedException e) {
218                 e.printStackTrace();
219                 logger.debug("An interrupt Exception was thrown");
220                 fail("An interrupt Exception was thrown");
221             }
222             
223             /*
224              * Simulate a success response from APPC and insert
225              * the response into the working memory
226              */
227             LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
228             LCMResponse appcResponse = new LCMResponse(appcRequest);
229             appcResponse.getStatus().setCode(400);
230             appcResponse.getStatus().setMessage("AppC success");
231             dmaapResponse.setBody(appcResponse);
232             kieSession.insert(dmaapResponse);
233             
234             /* 
235              * Give time for processing
236              */
237             try {
238                 Thread.sleep(4000);
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              * Make sure the next notification is delivered
247              */
248             obj = engine.subscribe("UEB", "POLICY-CL-MGT");
249             assertNotNull(obj);
250             logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
251             
252             /*
253              * The ControlLoopNotification should be
254              * an OPERATION_SUCCESS
255              */
256             assertTrue(obj instanceof VirtualControlLoopNotification);
257             assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION_SUCCESS));
258             
259             /* 
260              * Now simulate the abatement sent from DCAE
261              */
262             try {
263                 sendAbatement(pair.a, requestID, triggerSourceName);
264             } catch (InterruptedException e1) {
265                 e1.printStackTrace();
266                 logger.debug("Abatement could not be sent");
267                 fail("Abatement could not be sent");
268             }
269             
270             /*
271              * Give time to finish processing
272              */
273             try {
274                 Thread.sleep(20000);
275             } catch (InterruptedException e) {
276                 e.printStackTrace();
277                 logger.debug("An interrupt Exception was thrown");
278                 fail("An interrupt Exception was thrown");
279             }     
280             
281             /*
282              * This should be the final notification from the Policy Engine
283              */
284             obj = engine.subscribe("UEB", "POLICY-CL-MGT");
285             assertNotNull(obj);
286             logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
287             
288             /*
289              * The ControlLoopNotification should be of type FINAL_SUCCESS
290              */
291             assertTrue(obj instanceof VirtualControlLoopNotification);
292             assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.FINAL_SUCCESS));
293             
294             /*
295              * One final check to make sure the lock is released 
296              */
297             assertFalse(PolicyGuard.isLocked(TargetType.VNF, triggerSourceName, requestID));
298         }
299         else {
300             fail("Operation Denied by Guard");
301         }
302         
303         /*
304          * This will stop the thread that is firing the rules
305          */
306         kieSession.halt();
307         
308         /*
309          * The only fact in memory should be Params
310          */
311         assertEquals(1, kieSession.getFactCount());
312         
313         /*
314          * Print what's left in memory
315          */
316         dumpFacts(kieSession);
317         
318         /*
319          * Gracefully shut down the kie session
320          */
321         kieSession.dispose();
322     }
323
324     /**
325      * This method will start a kie session and instantiate 
326      * the Policy Engine.
327      * 
328      * @param droolsTemplate
329      *          the DRL rules file
330      * @param yamlFile
331      *          the yaml file containing the policies
332      * @param policyScope
333      *          scope for policy
334      * @param policyName
335      *          name of the policy
336      * @param policyVersion
337      *          version of the policy          
338      * @return the kieSession to be used to insert facts 
339      * @throws IOException
340      */
341     private KieSession startSession(String droolsTemplate, 
342             String yamlFile, 
343             String policyScope, 
344             String policyName, 
345             String policyVersion) throws IOException {
346         
347         /*
348          * Load policies from yaml
349          */
350         pair = Util.loadYaml(yamlFile);
351         assertNotNull(pair);
352         assertNotNull(pair.a);
353         assertNotNull(pair.a.getControlLoop());
354         assertNotNull(pair.a.getControlLoop().getControlLoopName());
355         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
356         
357         /* 
358          * Construct a kie session
359          */
360         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
361                 pair.a.getControlLoop().getControlLoopName(), 
362                 policyScope, 
363                 policyName, 
364                 policyVersion, 
365                 URLEncoder.encode(pair.b, "UTF-8"));
366         
367         /*
368          * Retrieve the Policy Engine
369          */
370         engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
371         
372         logger.debug("============");
373         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
374         logger.debug("============");
375         
376         return kieSession;
377     }
378     
379     /**
380      * This method is used to simulate event messages from DCAE
381      * that start the control loop (onset message).
382      * 
383      * @param policy the controlLoopName comes from the policy 
384      * @param requestID the requestId for this event
385      * @param triggerSourceName 
386      * @throws InterruptedException
387      */
388     protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
389         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
390         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
391         event.requestID = requestID;
392         event.target = "generic-vnf.vnf-id";
393         event.closedLoopAlarmStart = Instant.now();
394         event.AAI = new HashMap<>();
395         event.AAI.put("cloud-region.identity-url", "foo");
396         event.AAI.put("vserver.selflink", "bar");
397         event.AAI.put("vserver.is-closed-loop-disabled", "false");
398         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfId");
399         event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
400         kieSession.insert(event);
401         Thread.sleep(1000);
402     }
403     
404     /**
405      * This method is used to simulate event messages from DCAE
406      * that end the control loop (abatement message).
407      * 
408      * @param policy the controlLoopName comes from the policy 
409      * @param requestID the requestId for this event
410      * @param triggerSourceName 
411      * @throws InterruptedException
412      */
413     protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
414         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
415         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
416         event.requestID = requestID;
417         event.target = "generic-vnf.vnf-id";
418         event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
419         event.closedLoopAlarmEnd = Instant.now();
420         event.AAI = new HashMap<>();
421         event.AAI.put("cloud-region.identity-url", "foo");
422         event.AAI.put("vserver.selflink", "bar");
423         event.AAI.put("vserver.is-closed-loop-disabled", "false");
424         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfId");
425         event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
426         kieSession.insert(event);
427     }
428     
429     /**
430      * This method will dump all the facts in the working memory.
431      * 
432      * @param kieSession the session containing the facts
433      */
434     public void dumpFacts(KieSession kieSession) {
435         logger.debug("Fact Count: {}", kieSession.getFactCount());
436         for (FactHandle handle : kieSession.getFactHandles()) {
437             logger.debug("FACT: {}", handle);
438         }
439     }
440 }