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