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