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