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