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