Removed checkstyle warnings
[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-2018 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.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.PolicyController;
56 import org.onap.policy.drools.system.PolicyEngine;
57 import org.onap.policy.drools.utils.logging.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",
89                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
90         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
91                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
92         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
93
94         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
95                 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
96                 1111);
97
98         try {
99             Util.buildAaiSim();
100             Util.buildVfcSim();
101             Util.buildGuardSim();
102         } catch (Exception e) {
103             fail(e.getMessage());
104         }
105         /*
106          * 
107          * Start the kie session
108          */
109         try {
110             kieSession = startSession(
111                     "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
112                     "src/test/resources/yaml/policy_ControlLoop_VFC.yaml", "type=operational", "CL_VoLTE", "v2.0");
113         } catch (IOException e) {
114             e.printStackTrace();
115             logger.debug("Could not create kieSession");
116             fail("Could not create kieSession");
117         }
118     }
119
120     @AfterClass
121     public static void tearDownSimulator() {
122
123         /*
124          * Gracefully shut down the kie session
125          */
126         kieSession.dispose();
127
128         PolicyEngine.manager.stop();
129         HttpServletServer.factory.destroy();
130         PolicyController.factory.shutdown();
131         TopicEndpoint.manager.shutdown();
132     }
133
134     @Test
135     public void successTest() throws IOException {
136
137         /*
138          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
139          * to be pulled from the queue
140          */
141         for (TopicSink sink : noopTopics) {
142             assertTrue(sink.start());
143             sink.register(this);
144         }
145
146         /*
147          * Create a unique requestId
148          */
149         requestID = UUID.randomUUID();
150
151         /*
152          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
153          * through 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 notify that there is an event ready
175          * to be pulled from the queue
176          */
177         for (TopicSink sink : noopTopics) {
178             assertTrue(sink.start());
179             sink.register(this);
180         }
181
182         /*
183          * Create a unique requestId
184          */
185         requestID = UUID.randomUUID();
186
187         /*
188          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
189          * through the rules
190          */
191
192         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
193         event.setClosedLoopControlName(pair.a.getControlLoop().getControlLoopName());
194         event.setRequestId(UUID.randomUUID());
195         event.setClosedLoopEventClient("tca.instance00009");
196         event.setTargetType(ControlLoopTargetType.VM);
197         event.setTarget("vserver.vserver-name");
198         event.setFrom("DCAE");
199         event.setClosedLoopAlarmStart(Instant.now());
200         event.setAai(new HashMap<String, String>());
201         event.getAai().put("vserver.vserver-name", "nullRequest");
202         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
203         kieSession.insert(event);
204
205         kieSession.fireUntilHalt();
206
207         /*
208          * The only fact in memory should be Params
209          */
210         assertEquals(1, kieSession.getFactCount());
211
212         /*
213          * Print what's left in memory
214          */
215         dumpFacts(kieSession);
216     }
217
218     /**
219      * This method will start a kie session and instantiate the Policy Engine.
220      *
221      * @param droolsTemplate the DRL rules file
222      * @param yamlFile the yaml file containing the policies
223      * @param policyScope scope for policy
224      * @param policyName name of the policy
225      * @param policyVersion version of the policy
226      * @return the kieSession to be used to insert facts
227      * @throws IOException
228      */
229     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
230             String policyName, String policyVersion) throws IOException {
231
232         /*
233          * Load policies from yaml
234          */
235         pair = Util.loadYaml(yamlFile);
236         assertNotNull(pair);
237         assertNotNull(pair.a);
238         assertNotNull(pair.a.getControlLoop());
239         assertNotNull(pair.a.getControlLoop().getControlLoopName());
240         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
241
242         /*
243          * Construct a kie session
244          */
245         final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(),
246                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8"));
247
248         /*
249          * Retrieve the Policy Engine
250          */
251
252         logger.debug("============");
253         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
254         logger.debug("============");
255
256         return kieSession;
257     }
258
259     /*
260      * (non-Javadoc)
261      * 
262      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
263      */
264     @Override
265     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
266         /*
267          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
268          * of type active
269          */
270         Object obj = null;
271         if ("POLICY-CL-MGT".equals(topic)) {
272             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
273                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
274         }
275         assertNotNull(obj);
276         if (obj instanceof VirtualControlLoopNotification) {
277             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
278             String policyName = notification.getPolicyName();
279             if (policyName.endsWith("EVENT")) {
280                 logger.debug("Rule Fired: " + notification.getPolicyName());
281                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
282             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
283                 logger.debug("Rule Fired: " + notification.getPolicyName());
284                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
285                 assertNotNull(notification.getMessage());
286                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
287             } else if (policyName.endsWith("GUARD.RESPONSE")) {
288                 logger.debug("Rule Fired: " + notification.getPolicyName());
289                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
290                 assertNotNull(notification.getMessage());
291                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
292             } else if (policyName.endsWith("GUARD_PERMITTED")) {
293                 logger.debug("Rule Fired: " + notification.getPolicyName());
294                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
295                 assertNotNull(notification.getMessage());
296                 assertTrue(notification.getMessage().startsWith("actor=VFC"));
297             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
298                 logger.debug("Rule Fired: " + notification.getPolicyName());
299                 kieSession.halt();
300                 logger.debug("The operation timed out");
301                 fail("Operation Timed Out");
302             } else if (policyName.endsWith("VFC.RESPONSE")) {
303                 logger.debug("Rule Fired: " + notification.getPolicyName());
304                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
305                 assertNotNull(notification.getMessage());
306                 assertTrue(notification.getMessage().startsWith("actor=VFC"));
307             } else if (policyName.endsWith("EVENT.MANAGER")) {
308                 logger.debug("Rule Fired: " + notification.getPolicyName());
309                 if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) {
310                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
311                 } else {
312                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
313                 }
314                 kieSession.halt();
315             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
316                 logger.debug("Rule Fired: " + notification.getPolicyName());
317                 kieSession.halt();
318                 logger.debug("The control loop timed out");
319                 fail("Control Loop Timed Out");
320             }
321         } else if (obj instanceof VFCRequest) {
322             logger.debug("\n============ VFC received the request!!! ===========\n");
323         }
324     }
325
326     /**
327      * This method is used to simulate event messages from DCAE that start the control loop (onset
328      * message) or end the control loop (abatement message).
329      * 
330      * @param policy the controlLoopName comes from the policy
331      * @param requestID the requestId for this event
332      * @param status could be onset or abated
333      */
334     protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
335         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
336         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
337         event.setRequestId(UUID.randomUUID());
338         event.setClosedLoopEventClient("tca.instance00009");
339         event.setTargetType(ControlLoopTargetType.VM);
340         event.setTarget("vserver.vserver-name");
341         event.setFrom("DCAE");
342         event.setClosedLoopAlarmStart(Instant.now());
343         event.setAai(new HashMap<String, String>());
344         event.getAai().put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
345         event.getAai().put("vserver.vserver-id", "vserver-id-16102016-aai3255-data-11-1");
346         event.getAai().put("generic-vnf.vnf-id", "vnf-id-16102016-aai3255-data-11-1");
347         event.getAai().put("service-instance.service-instance-id", "service-instance-id-16102016-aai3255-data-11-1");
348         event.getAai().put("vserver.is-closed-loop-disabled", "false");
349         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
350         kieSession.insert(event);
351     }
352
353     public static void dumpFacts(KieSession kieSession) {
354         logger.debug("Fact Count: " + kieSession.getFactCount());
355         for (FactHandle handle : kieSession.getFactHandles()) {
356             logger.debug("FACT: " + handle);
357         }
358     }
359
360 }
361