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