f18b440d70badbc56c4f4c4041021fbeb4db2f4c
[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.List;
30 import java.util.Properties;
31 import java.util.UUID;
32
33 import org.junit.AfterClass;
34 import org.junit.BeforeClass;
35 import org.junit.Test;
36 import org.kie.api.runtime.KieSession;
37 import org.kie.api.runtime.rule.FactHandle;
38 import org.onap.policy.appclcm.LCMRequest;
39 import org.onap.policy.appclcm.LCMRequestWrapper;
40 import org.onap.policy.appclcm.LCMResponse;
41 import org.onap.policy.appclcm.LCMResponseWrapper;
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.event.comm.Topic.CommInfrastructure;
48 import org.onap.policy.drools.event.comm.TopicEndpoint;
49 import org.onap.policy.drools.event.comm.TopicListener;
50 import org.onap.policy.drools.event.comm.TopicSink;
51 import org.onap.policy.drools.http.server.HttpServletServer;
52 import org.onap.policy.drools.properties.PolicyProperties;
53 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
54 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
55 import org.onap.policy.drools.system.PolicyEngine;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 public class VCPEControlLoopTest implements TopicListener {
60
61     private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class);
62     
63     private static List<? extends TopicSink> noopTopics;
64     
65     private static KieSession kieSession;
66     private static Util.Pair<ControlLoopPolicy, String> pair;
67     private UUID requestID;
68     
69     static {
70         /* Set environment properties */
71         Util.setAAIProps();
72         Util.setGuardProps();
73         Util.setPUProp();
74     }
75     
76     @BeforeClass
77     public static void setUpSimulator() {
78         PolicyEngine.manager.configure(new Properties());
79         assertTrue(PolicyEngine.manager.start());
80         Properties noopSinkProperties = new Properties();
81         noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
82         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LCMRequestWrapper");
83         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson", "org.onap.policy.appclcm.util.Serialization,gson");
84         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", "org.onap.policy.controlloop.VirtualControlLoopNotification");
85         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", "org.onap.policy.controlloop.util.Serialization,gsonPretty");
86         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
87         
88         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, 1111);
89         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ", "org.onap.policy.appclcm.LCMRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
90         try {
91             Util.buildAaiSim();
92             Util.buildGuardSim();
93         } catch (Exception e) {
94             fail(e.getMessage());
95         }
96         /*
97          * Start the kie session
98          */
99         try {
100             kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", 
101                         "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
102                         "service=ServiceDemo;resource=Res1Demo;type=operational", 
103                         "CL_vCPE", 
104                         "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
105         } catch (IOException e) {
106             e.printStackTrace();
107             logger.debug("Could not create kieSession");
108             fail("Could not create kieSession");
109         }
110     }
111
112     @AfterClass
113     public static void tearDownSimulator() {
114         /*
115          * Gracefully shut down the kie session
116          */
117         kieSession.dispose();
118         
119         HttpServletServer.factory.destroy();
120         PolicyEngine.manager.shutdown();
121         TopicEndpoint.manager.shutdown();
122         PolicyEngine.manager.stop();
123     }
124     
125     @Test
126     public void successTest() {
127         
128         /*
129          * Allows the PolicyEngine to callback to this object to
130          * notify that there is an event ready to be pulled 
131          * from the queue
132          */
133         for (TopicSink sink : noopTopics) {
134             assertTrue(sink.start());
135             sink.register(this);
136         }
137         
138         /*
139          * Create a unique requestId
140          */
141         requestID = UUID.randomUUID();
142         
143         /* 
144          * Simulate an onset event the policy engine will 
145          * receive from DCAE to kick off processing through
146          * the rules
147          */
148         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
149
150         
151         kieSession.fireUntilHalt();
152         
153         /*
154          * The only fact in memory should be Params
155          */
156         assertEquals(1, kieSession.getFactCount());
157         
158         /*
159          * Print what's left in memory
160          */
161         dumpFacts(kieSession);
162     }
163     
164     @Test
165     public void aaiGetFailTest() {
166         
167         /*
168          * Allows the PolicyEngine to callback to this object to
169          * notify that there is an event ready to be pulled 
170          * from the queue
171          */
172         for (TopicSink sink : noopTopics) {
173             assertTrue(sink.start());
174             sink.register(this);
175         }
176         
177         /*
178          * Create a unique requestId
179          */
180         requestID = UUID.randomUUID();
181         
182         /* 
183          * Simulate an onset event the policy engine will 
184          * receive from DCAE to kick off processing through
185          * the rules
186          */
187         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail");
188
189         
190         kieSession.fireUntilHalt();
191         
192         /*
193          * The only fact in memory should be Params
194          */
195         assertEquals(1, kieSession.getFactCount());
196         
197         /*
198          * Print what's left in memory
199          */
200         dumpFacts(kieSession);
201         
202     }
203
204     /**
205      * This method will start a kie session and instantiate 
206      * the Policy Engine.
207      * 
208      * @param droolsTemplate
209      *          the DRL rules file
210      * @param yamlFile
211      *          the yaml file containing the policies
212      * @param policyScope
213      *          scope for policy
214      * @param policyName
215      *          name of the policy
216      * @param policyVersion
217      *          version of the policy          
218      * @return the kieSession to be used to insert facts 
219      * @throws IOException
220      */
221     private static KieSession startSession(String droolsTemplate, 
222             String yamlFile, 
223             String policyScope, 
224             String policyName, 
225             String policyVersion) throws IOException {
226         
227         /*
228          * Load policies from yaml
229          */
230         pair = Util.loadYaml(yamlFile);
231         assertNotNull(pair);
232         assertNotNull(pair.a);
233         assertNotNull(pair.a.getControlLoop());
234         assertNotNull(pair.a.getControlLoop().getControlLoopName());
235         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
236         
237         /* 
238          * Construct a kie session
239          */
240         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
241                 pair.a.getControlLoop().getControlLoopName(), 
242                 policyScope, 
243                 policyName, 
244                 policyVersion, 
245                 URLEncoder.encode(pair.b, "UTF-8"));
246         
247         /*
248          * Retrieve the Policy Engine
249          */
250         
251         logger.debug("============");
252         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
253         logger.debug("============");
254         
255         return kieSession;
256     }
257     
258     /*
259      * (non-Javadoc)
260      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
261      */
262     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
263         /*
264          * Pull the object that was sent out to DMAAP and make
265          * sure it is a ControlLoopNoticiation of type active
266          */
267         Object obj = null;
268         if ("POLICY-CL-MGT".equals(topic)) {
269                 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
270         }
271         else if ("APPC-LCM-READ".equals(topic))
272                 obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.appclcm.LCMRequestWrapper.class);
273         assertNotNull(obj);
274         if (obj instanceof VirtualControlLoopNotification) {
275             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
276             String policyName = notification.policyName;
277             if (policyName.endsWith("EVENT")) {
278                 logger.debug("Rule Fired: " + notification.policyName);
279                 if ("getFail".equals(notification.AAI.get("generic-vnf.vnf-name"))) {
280                         assertEquals(ControlLoopNotificationType.REJECTED, notification.notification);
281                         kieSession.halt();
282                 }
283                 else {
284                     assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
285                 }
286             }
287             else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
288                 logger.debug("Rule Fired: " + notification.policyName);
289                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
290                 assertNotNull(notification.message);
291                 assertTrue(notification.message.startsWith("Sending guard query"));
292             }
293             else if (policyName.endsWith("GUARD.RESPONSE")) {
294                 logger.debug("Rule Fired: " + notification.policyName);
295                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
296                 assertNotNull(notification.message);
297                 assertTrue(notification.message.toLowerCase().endsWith("permit"));
298             }
299             else if (policyName.endsWith("GUARD_PERMITTED")) {
300                 logger.debug("Rule Fired: " + notification.policyName);
301                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
302                 assertNotNull(notification.message);
303                 assertTrue(notification.message.startsWith("actor=APPC"));
304             }
305             else if (policyName.endsWith("OPERATION.TIMEOUT")) {
306                 logger.debug("Rule Fired: " + notification.policyName);
307                 kieSession.halt();
308                 logger.debug("The operation timed out");
309                 fail("Operation Timed Out");
310             }
311             else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
312                 logger.debug("Rule Fired: " + notification.policyName);
313                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
314                 assertNotNull(notification.message);
315                 assertTrue(notification.message.startsWith("actor=APPC"));
316                 sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED);
317             }
318             else if (policyName.endsWith("EVENT.MANAGER")) {
319                 logger.debug("Rule Fired: " + notification.policyName);
320                 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
321                 kieSession.halt();
322             }
323             else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
324                 logger.debug("Rule Fired: " + notification.policyName);
325                 kieSession.halt();
326                 logger.debug("The control loop timed out");
327                 fail("Control Loop Timed Out");
328             }
329         }
330         else if (obj instanceof LCMRequestWrapper) {
331             /*
332              * The request should be of type LCMRequestWrapper
333              * and the subrequestid should be 1
334              */
335             LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
336             LCMRequest appcRequest = dmaapRequest.getBody();
337             assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
338             
339             logger.debug("\n============ APPC received the request!!! ===========\n");
340             
341             /*
342              * Simulate a success response from APPC and insert
343              * the response into the working memory
344              */
345             LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
346             LCMResponse appcResponse = new LCMResponse(appcRequest);
347             appcResponse.getStatus().setCode(400);
348             appcResponse.getStatus().setMessage("AppC success");
349             dmaapResponse.setBody(appcResponse);
350             kieSession.insert(dmaapResponse);
351         }        
352     }
353     
354     /**
355      * This method is used to simulate event messages from DCAE
356      * that start the control loop (onset message) or end the
357      * control loop (abatement message).
358      * 
359      * @param policy the controlLoopName comes from the policy 
360      * @param requestID the requestId for this event
361      * @param status could be onset or abated
362      */
363     protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
364         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
365         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
366         event.requestID = requestID;
367         event.target = "generic-vnf.vnf-name";
368         event.closedLoopAlarmStart = Instant.now();
369         event.AAI = new HashMap<>();
370         event.AAI.put("generic-vnf.vnf-name", "testGenericVnfName");
371         event.closedLoopEventStatus = status;
372         kieSession.insert(event);
373     }
374     
375     protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String vnfName) {
376         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
377         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
378         event.requestID = requestID;
379         event.target = "generic-vnf.vnf-name";
380         event.closedLoopAlarmStart = Instant.now();
381         event.AAI = new HashMap<>();
382         event.AAI.put("generic-vnf.vnf-name", vnfName);
383         event.closedLoopEventStatus = status;
384         kieSession.insert(event);
385     }
386     
387     /**
388      * This method will dump all the facts in the working memory.
389      * 
390      * @param kieSession the session containing the facts
391      */
392     public void dumpFacts(KieSession kieSession) {
393         logger.debug("Fact Count: {}", kieSession.getFactCount());
394         for (FactHandle handle : kieSession.getFactHandles()) {
395             logger.debug("FACT: {}", handle);
396         }
397     }
398     
399 }