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