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