42742b261421d7f98d5ed1edfb1bbc999834705f
[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 import org.junit.AfterClass;
36 import org.junit.BeforeClass;
37 import org.junit.Test;
38 import org.kie.api.runtime.KieSession;
39 import org.kie.api.runtime.rule.FactHandle;
40 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
41 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
42 import org.onap.policy.common.endpoints.event.comm.TopicListener;
43 import org.onap.policy.common.endpoints.event.comm.TopicSink;
44 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
45 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
46 import org.onap.policy.controlloop.ControlLoopEventStatus;
47 import org.onap.policy.controlloop.ControlLoopNotificationType;
48 import org.onap.policy.controlloop.ControlLoopTargetType;
49 import org.onap.policy.controlloop.VirtualControlLoopEvent;
50 import org.onap.policy.controlloop.VirtualControlLoopNotification;
51 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
52 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
53 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
54 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
55 import org.onap.policy.drools.system.PolicyController;
56 import org.onap.policy.drools.system.PolicyEngine;
57 import org.onap.policy.drools.utils.logging.LoggerUtil;
58 import org.onap.policy.sdnc.SdncRequest;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 public class CcvpnBwControlLoopTest implements TopicListener {
63
64     private static final Logger logger = LoggerFactory.getLogger(CcvpnBwControlLoopTest.class);
65
66     private static List<? extends TopicSink> noopTopics;
67
68     private static KieSession kieSession;
69     private static SupportUtil.Pair<ControlLoopPolicy, String> pair;
70
71     static {
72         /* Set environment properties */
73         SupportUtil.setAaiProps();
74         SupportUtil.setSdncProps();
75         SupportUtil.setGuardProps();
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 = TopicEndpointManager.getManager().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             SupportUtil.buildGuardSim();
106         } catch (Exception e) {
107             fail(e.getMessage());
108         }
109
110         /*
111          *
112          * Start the kie session
113          */
114         try {
115             kieSession = startSession(
116                     "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
117                     + "src/main/resources/__closedLoopControlName__.drl",
118                     "src/test/resources/yaml/policy_ControlLoop_CCVPN_BW.yaml", "type=operational",
119                     "BandwidthOnDemand", "2.0.0");
120         } catch (IOException e) {
121             e.printStackTrace();
122             logger.debug("Could not create kieSession");
123             fail("Could not create kieSession");
124         }
125     }
126
127     /**
128      * Tear down the simulator.
129      */
130     @AfterClass
131     public static void tearDownSimulator() {
132
133         /*
134          * Gracefully shut down the kie session
135          */
136         kieSession.dispose();
137
138         PolicyEngine.manager.stop();
139         HttpServletServerFactoryInstance.getServerFactory().destroy();
140         PolicyController.factory.shutdown();
141         TopicEndpointManager.getManager().shutdown();
142     }
143
144     @Test
145     public void successTest() throws IOException {
146
147         /*
148          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
149          * to be pulled from the queue
150          */
151         for (TopicSink sink : noopTopics) {
152             assertTrue(sink.start());
153             sink.register(this);
154         }
155
156         /*
157          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
158          * through the rules
159          */
160         sendEvent(pair.first);
161
162         kieSession.fireUntilHalt();
163
164         // allow object clean-up
165         kieSession.fireAllRules();
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          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
192          * through the rules
193          */
194
195         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
196         event.setClosedLoopControlName(pair.first.getControlLoop().getControlLoopName());
197         event.setRequestId(UUID.randomUUID());
198         event.setClosedLoopEventClient("DCAE.HolmesInstance");
199         event.setTargetType(ControlLoopTargetType.VM);
200         event.setTarget("vserver.vserver-name");
201         event.setFrom("DCAE");
202         event.setClosedLoopAlarmStart(Instant.now());
203         event.setAai(new HashMap<String, String>());
204         event.getAai().put("vserver.vserver-name", "nullRequest");
205         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
206         kieSession.insert(event);
207
208         kieSession.fireUntilHalt();
209
210         // allow object clean-up
211         kieSession.fireAllRules();
212
213         /*
214          * The only fact in memory should be Params
215          */
216         assertEquals(1, kieSession.getFactCount());
217
218         /*
219          * Print what's left in memory
220          */
221         dumpFacts(kieSession);
222     }
223
224     /**
225      * This method will start a kie session and instantiate the Policy Engine.
226      *
227      * @param droolsTemplate the DRL rules file
228      * @param yamlFile the yaml file containing the policies
229      * @param policyScope scope for policy
230      * @param policyName name of the policy
231      * @param policyVersion version of the policy
232      * @return the kieSession to be used to insert facts
233      * @throws IOException IO Exception
234      */
235     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
236             String policyName, String policyVersion) throws IOException {
237
238         /*
239          * Load policies from yaml
240          */
241         pair = SupportUtil.loadYaml(yamlFile);
242         assertNotNull(pair);
243         assertNotNull(pair.first);
244         assertNotNull(pair.first.getControlLoop());
245         assertNotNull(pair.first.getControlLoop().getControlLoopName());
246         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
247
248         /*
249          * Construct a kie session
250          */
251         final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
252                 pair.first.getControlLoop().getControlLoopName(),
253                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second,
254                                                                           StandardCharsets.UTF_8.name()));
255
256         /*
257          * Retrieve the Policy Engine
258          */
259
260         logger.debug("============");
261         logger.debug(URLEncoder.encode(pair.second, StandardCharsets.UTF_8.name()));
262         logger.debug("============");
263
264         return kieSession;
265     }
266
267     /*
268      * (non-Javadoc)
269      *
270      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
271      */
272     @Override
273     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
274         /*
275          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
276          * of type active
277          */
278         Object obj = null;
279         if ("POLICY-CL-MGT".equals(topic)) {
280             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
281                     VirtualControlLoopNotification.class);
282         }
283         assertNotNull(obj);
284         if (obj instanceof VirtualControlLoopNotification) {
285             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
286             String policyName = notification.getPolicyName();
287             if (policyName.endsWith("EVENT")) {
288                 logger.debug("Rule Fired: " + notification.getPolicyName());
289                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
290             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
291                 logger.debug("Rule Fired: " + notification.getPolicyName());
292                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
293                 assertNotNull(notification.getMessage());
294                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
295             } else if (policyName.endsWith("GUARD.RESPONSE")) {
296                 logger.debug("Rule Fired: " + notification.getPolicyName());
297                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
298                 assertNotNull(notification.getMessage());
299                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
300             } else if (policyName.endsWith("GUARD_PERMITTED")) {
301                 logger.debug("Rule Fired: " + notification.getPolicyName());
302                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
303                 assertNotNull(notification.getMessage());
304                 assertTrue(notification.getMessage().startsWith("actor=SDNC"));
305             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
306                 logger.debug("Rule Fired: " + notification.getPolicyName());
307                 kieSession.halt();
308                 logger.debug("The operation timed out");
309                 fail("Operation Timed Out");
310             } else if (policyName.endsWith("SDNC.RESPONSE")) {
311                 logger.debug("Rule Fired: " + notification.getPolicyName());
312                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
313                 assertNotNull(notification.getMessage());
314                 assertTrue(notification.getMessage().startsWith("actor=SDNC"));
315             } else if (policyName.endsWith("EVENT.MANAGER")) {
316                 logger.debug("Rule Fired: " + notification.getPolicyName());
317                 if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) {
318                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
319                 } else {
320                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
321                 }
322                 kieSession.halt();
323             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
324                 logger.debug("Rule Fired: " + notification.getPolicyName());
325                 kieSession.halt();
326                 logger.debug("The control loop timed out");
327                 fail("Control Loop Timed Out");
328             }
329         } else if (obj instanceof SdncRequest) {
330             logger.debug("\n============ SDNC received the request!!! ===========\n");
331         }
332     }
333
334     /**
335      * This method is used to simulate event messages from DCAE that start the control loop (onset
336      * message) or end the control loop (abatement message).
337      *
338      * @param policy the controlLoopName comes from the policy
339      */
340     protected void sendEvent(ControlLoopPolicy policy) {
341         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
342         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
343         event.setRequestId(UUID.randomUUID());
344         event.setClosedLoopEventClient("DCAE.HolmesInstance");
345         event.setTargetType(ControlLoopTargetType.VM);
346         event.setTarget("vserver.vserver-name");
347         event.setFrom("DCAE");
348         event.setClosedLoopAlarmStart(Instant.now());
349         event.setAai(new HashMap<String, String>());
350         event.getAai().put("vserver.vserver-name", "TBD");
351         event.getAai().put("globalSubscriberId", "e151059a-d924-4629-845f-264db19e50b4");
352         event.getAai().put("serviceType", "siteService");
353         event.getAai().put("service-instance.service-instance-id", "service-instance-id-example-1");
354         event.getAai().put("vserver.is-closed-loop-disabled", "false");
355         event.getAai().put("vserver.prov-status", "ACTIVE");
356         event.getAai().put("bandwidth", "500");
357         event.getAai().put("bandwidth-change-time", "20190326-05:20:38:668");
358         event.getAai().put("vnfId", "vnf-id");
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 }