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