449a90fe05e55e267301ac8705af51c8dc73bf51
[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         /*
168          * The only fact in memory should be Params
169          */
170         assertEquals(1, kieSession.getFactCount());
171
172         /*
173          * Print what's left in memory
174          */
175         dumpFacts(kieSession);
176     }
177
178     @Test
179     public void nullRequestTest() throws IOException {
180
181         /*
182          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
183          * to be pulled from the queue
184          */
185         for (TopicSink sink : noopTopics) {
186             assertTrue(sink.start());
187             sink.register(this);
188         }
189
190         /*
191          * Create a unique requestId
192          */
193         requestId = UUID.randomUUID();
194
195         /*
196          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
197          * through the rules
198          */
199
200         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
201         event.setClosedLoopControlName(pair.first.getControlLoop().getControlLoopName());
202         event.setRequestId(UUID.randomUUID());
203         event.setClosedLoopEventClient("tca.instance00009");
204         event.setTargetType(ControlLoopTargetType.VM);
205         event.setTarget("vserver.vserver-name");
206         event.setFrom("DCAE");
207         event.setClosedLoopAlarmStart(Instant.now());
208         event.setAai(new HashMap<String, String>());
209         event.getAai().put("vserver.vserver-name", "nullRequest");
210         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
211         kieSession.insert(event);
212
213         kieSession.fireUntilHalt();
214
215         /*
216          * The only fact in memory should be Params
217          */
218         assertEquals(1, kieSession.getFactCount());
219
220         /*
221          * Print what's left in memory
222          */
223         dumpFacts(kieSession);
224     }
225
226     /**
227      * This method will start a kie session and instantiate the Policy Engine.
228      *
229      * @param droolsTemplate the DRL rules file
230      * @param yamlFile the yaml file containing the policies
231      * @param policyScope scope for policy
232      * @param policyName name of the policy
233      * @param policyVersion version of the policy
234      * @return the kieSession to be used to insert facts
235      * @throws IOException IO Exception
236      */
237     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
238             String policyName, String policyVersion) throws IOException {
239
240         /*
241          * Load policies from yaml
242          */
243         pair = Util.loadYaml(yamlFile);
244         assertNotNull(pair);
245         assertNotNull(pair.first);
246         assertNotNull(pair.first.getControlLoop());
247         assertNotNull(pair.first.getControlLoop().getControlLoopName());
248         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
249
250         /*
251          * Construct a kie session
252          */
253         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
254                 pair.first.getControlLoop().getControlLoopName(),
255                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
256
257         /*
258          * Retrieve the Policy Engine
259          */
260
261         logger.debug("============");
262         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
263         logger.debug("============");
264
265         return kieSession;
266     }
267
268     /*
269      * (non-Javadoc)
270      * 
271      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
272      */
273     @Override
274     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
275         /*
276          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
277          * of type active
278          */
279         Object obj = null;
280         if ("POLICY-CL-MGT".equals(topic)) {
281             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
282                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
283         }
284         assertNotNull(obj);
285         if (obj instanceof VirtualControlLoopNotification) {
286             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
287             String policyName = notification.getPolicyName();
288             if (policyName.endsWith("EVENT")) {
289                 logger.debug("Rule Fired: " + notification.getPolicyName());
290                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
291             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
292                 logger.debug("Rule Fired: " + notification.getPolicyName());
293                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
294                 assertNotNull(notification.getMessage());
295                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
296             } else if (policyName.endsWith("GUARD.RESPONSE")) {
297                 logger.debug("Rule Fired: " + notification.getPolicyName());
298                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
299                 assertNotNull(notification.getMessage());
300                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
301             } else if (policyName.endsWith("GUARD_PERMITTED")) {
302                 logger.debug("Rule Fired: " + notification.getPolicyName());
303                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
304                 assertNotNull(notification.getMessage());
305                 assertTrue(notification.getMessage().startsWith("actor=VFC"));
306             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
307                 logger.debug("Rule Fired: " + notification.getPolicyName());
308                 kieSession.halt();
309                 logger.debug("The operation timed out");
310                 fail("Operation Timed Out");
311             } else if (policyName.endsWith("VFC.RESPONSE")) {
312                 logger.debug("Rule Fired: " + notification.getPolicyName());
313                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
314                 assertNotNull(notification.getMessage());
315                 assertTrue(notification.getMessage().startsWith("actor=VFC"));
316             } else if (policyName.endsWith("EVENT.MANAGER")) {
317                 logger.debug("Rule Fired: " + notification.getPolicyName());
318                 if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) {
319                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
320                 } else {
321                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
322                 }
323                 kieSession.halt();
324             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
325                 logger.debug("Rule Fired: " + notification.getPolicyName());
326                 kieSession.halt();
327                 logger.debug("The control loop timed out");
328                 fail("Control Loop Timed Out");
329             }
330         } else if (obj instanceof VFCRequest) {
331             logger.debug("\n============ VFC received the request!!! ===========\n");
332         }
333     }
334
335     /**
336      * This method is used to simulate event messages from DCAE that start the control loop (onset
337      * message) or end the control loop (abatement message).
338      * 
339      * @param policy the controlLoopName comes from the policy
340      * @param requestID the requestId for this event
341      * @param status could be onset or abated
342      */
343     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
344         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
345         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
346         event.setRequestId(UUID.randomUUID());
347         event.setClosedLoopEventClient("tca.instance00009");
348         event.setTargetType(ControlLoopTargetType.VM);
349         event.setTarget("vserver.vserver-name");
350         event.setFrom("DCAE");
351         event.setClosedLoopAlarmStart(Instant.now());
352         event.setAai(new HashMap<String, String>());
353         event.getAai().put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
354         event.getAai().put("vserver.vserver-id", "vserver-id-16102016-aai3255-data-11-1");
355         event.getAai().put("generic-vnf.vnf-id", "vnf-id-16102016-aai3255-data-11-1");
356         event.getAai().put("service-instance.service-instance-id", "service-instance-id-16102016-aai3255-data-11-1");
357         event.getAai().put("vserver.is-closed-loop-disabled", "false");
358         event.getAai().put("vserver.prov-status", "ACTIVE");
359         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
360         kieSession.insert(event);
361     }
362
363     /**
364      * Dumps the kie session facts.
365      * 
366      * @param kieSession input session
367      */
368     public static void dumpFacts(KieSession kieSession) {
369         logger.debug("Fact Count: " + kieSession.getFactCount());
370         for (FactHandle handle : kieSession.getFactHandles()) {
371             logger.debug("FACT: " + handle);
372         }
373     }
374
375 }
376