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