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