fb4dc0265c6cd9f1fe0bb47a35f6007fcf9d4ae3
[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.assertEquals;
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.drools.PolicyEngineListener;
48 import org.onap.policy.drools.http.server.HttpServletServer;
49 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 public class VFWControlLoopTest implements PolicyEngineListener {
54
55     private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.class);
56     
57     private KieSession kieSession;
58     private Util.Pair<ControlLoopPolicy, String> pair;
59     private PolicyEngineJUnitImpl engine;
60     private UUID requestID;
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          * Allows the PolicyEngine to callback to this object to
104          * notify that there is an event ready to be pulled 
105          * from the queue
106          */
107         engine.addListener(this);
108         
109         /*
110          * Create a unique requestId
111          */
112         requestID = UUID.randomUUID();
113         
114         /* 
115          * Simulate an onset event the policy engine will 
116          * receive from DCAE to kick off processing through
117          * the rules
118          */
119         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
120         
121         kieSession.fireUntilHalt();
122         
123         /*
124          * The only fact in memory should be Params
125          */
126         assertEquals(1, kieSession.getFactCount());
127         
128         /*
129          * Print what's left in memory
130          */
131         dumpFacts(kieSession);
132         
133         /*
134          * Gracefully shut down the kie session
135          */
136         kieSession.dispose();
137     }
138     
139     /**
140      * This method will start a kie session and instantiate 
141      * the Policy Engine.
142      * 
143      * @param droolsTemplate
144      *          the DRL rules file
145      * @param yamlFile
146      *          the yaml file containing the policies
147      * @param policyScope
148      *          scope for policy
149      * @param policyName
150      *          name of the policy
151      * @param policyVersion
152      *          version of the policy          
153      * @return the kieSession to be used to insert facts 
154      * @throws IOException
155      */
156     private KieSession startSession(String droolsTemplate, 
157             String yamlFile, 
158             String policyScope, 
159             String policyName, 
160             String policyVersion) throws IOException {
161         
162         /*
163          * Load policies from yaml
164          */
165         pair = Util.loadYaml(yamlFile);
166         assertNotNull(pair);
167         assertNotNull(pair.a);
168         assertNotNull(pair.a.getControlLoop());
169         assertNotNull(pair.a.getControlLoop().getControlLoopName());
170         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
171         
172         /* 
173          * Construct a kie session
174          */
175         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
176                 pair.a.getControlLoop().getControlLoopName(), 
177                 policyScope, 
178                 policyName, 
179                 policyVersion, 
180                 URLEncoder.encode(pair.b, "UTF-8"));
181         
182         /*
183          * Retrieve the Policy Engine
184          */
185         engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
186         
187         logger.debug("============");
188         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
189         logger.debug("============");
190         
191         return kieSession;
192     }
193     
194     /*
195      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
196      */
197     public void newEventNotification(String topic) {
198         /*
199          * Pull the object that was sent out to DMAAP and make
200          * sure it is a ControlLoopNoticiation of type active
201          */
202         Object obj = engine.subscribe("UEB", topic);
203         assertNotNull(obj);
204         if (obj instanceof VirtualControlLoopNotification) {
205             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
206             String policyName = notification.policyName;
207             if (policyName.endsWith("EVENT")) {
208                 logger.debug("Rule Fired: " + notification.policyName);
209                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
210             }
211             else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
212                 logger.debug("Rule Fired: " + notification.policyName);
213                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
214                 assertNotNull(notification.message);
215                 assertTrue(notification.message.startsWith("Sending guard query"));
216             }
217             else if (policyName.endsWith("GUARD.RESPONSE")) {
218                 logger.debug("Rule Fired: " + notification.policyName);
219                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
220                 assertNotNull(notification.message);
221                 assertTrue(notification.message.endsWith("PERMIT"));
222             }
223             else if (policyName.endsWith("GUARD_PERMITTED")) {
224                 logger.debug("Rule Fired: " + notification.policyName);
225                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
226                 assertNotNull(notification.message);
227                 assertTrue(notification.message.startsWith("actor=APPC"));
228             }
229             else if (policyName.endsWith("OPERATION.TIMEOUT")) {
230                 logger.debug("Rule Fired: " + notification.policyName);
231                 kieSession.halt();
232                 logger.debug("The operation timed out");
233                 fail("Operation Timed Out");
234             }
235             else if (policyName.endsWith("APPC.RESPONSE")) {
236                 logger.debug("Rule Fired: " + notification.policyName);
237                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
238                 assertNotNull(notification.message);
239                 assertTrue(notification.message.startsWith("actor=APPC"));
240                 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
241             }
242             else if (policyName.endsWith("EVENT.MANAGER")) {
243                 logger.debug("Rule Fired: " + notification.policyName);
244                 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
245                 kieSession.halt();
246             }
247             else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
248                 logger.debug("Rule Fired: " + notification.policyName);
249                 kieSession.halt();
250                 logger.debug("The control loop timed out");
251                 fail("Control Loop Timed Out");
252             }
253         }
254         else if (obj instanceof Request) {
255             assertTrue(((Request)obj).getCommonHeader().SubRequestID.equals("1"));
256             
257             logger.debug("\n============ APPC received the request!!! ===========\n");
258             
259             /*
260              * Simulate a success response from APPC and insert
261              * the response into the working memory
262              */
263             Response appcResponse = new Response((Request)obj);
264             appcResponse.getStatus().Code = ResponseCode.SUCCESS.getValue();
265             appcResponse.getStatus().Value = "SUCCESS";
266             kieSession.insert(appcResponse);
267         }        
268     }
269     
270     /**
271      * This method is used to simulate event messages from DCAE
272      * that start the control loop (onset message) or end the
273      * control loop (abatement message).
274      * 
275      * @param policy the controlLoopName comes from the policy 
276      * @param requestID the requestId for this event
277      * @param status could be onset or abated
278      */
279     protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
280         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
281         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
282         event.requestID = requestID;
283         event.target = "generic-vnf.vnf-id";
284         event.closedLoopAlarmStart = Instant.now();
285         event.AAI = new HashMap<>();
286         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
287         event.closedLoopEventStatus = status;
288         kieSession.insert(event);
289     }
290     
291     /**
292      * This method will dump all the facts in the working memory.
293      * 
294      * @param kieSession the session containing the facts
295      */
296     public void dumpFacts(KieSession kieSession) {
297         logger.debug("Fact Count: {}", kieSession.getFactCount());
298         for (FactHandle handle : kieSession.getFactHandles()) {
299             logger.debug("FACT: {}", handle);
300         }
301     }
302 }