0ac9c48dffbd4e5b160ca0bd7da2471826c0f174
[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         SupportUtil.setGuardProps();
77         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
78     }
79
80     /**
81      * Setup the simulator.
82      */
83     @BeforeClass
84     public static void setUpSimulator() {
85         PolicyEngine.manager.configure(new Properties());
86         assertTrue(PolicyEngine.manager.start());
87         Properties noopSinkProperties = new Properties();
88         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
89         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
90                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
91         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
92                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
93         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
94
95         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
96                 .groupId("junit.groupId")
97                 .artifactId("junit.artifactId")
98                 .topic("POLICY-CL-MGT")
99                 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
100                 .protocolFilter(new JsonProtocolFilter())
101                 .modelClassLoaderHash(1111));
102
103         try {
104             SupportUtil.buildAaiSim();
105             SupportUtil.buildSdncSim();
106             SupportUtil.buildGuardSim();
107         } catch (Exception e) {
108             fail(e.getMessage());
109         }
110
111         /*
112          *
113          * Start the kie session
114          */
115         try {
116             kieSession = startSession(
117                     "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
118                     + "src/main/resources/__closedLoopControlName__.drl",
119                     "src/test/resources/yaml/policy_ControlLoop_CCVPN_BW.yaml", "type=operational",
120                     "BandwidthOnDemand", "2.0.0");
121         } catch (IOException e) {
122             e.printStackTrace();
123             logger.debug("Could not create kieSession");
124             fail("Could not create kieSession");
125         }
126     }
127
128     /**
129      * Tear down the simulator.
130      */
131     @AfterClass
132     public static void tearDownSimulator() {
133
134         /*
135          * Gracefully shut down the kie session
136          */
137         kieSession.dispose();
138
139         PolicyEngine.manager.stop();
140         HttpServletServer.factory.destroy();
141         PolicyController.factory.shutdown();
142         TopicEndpoint.manager.shutdown();
143     }
144
145     @Test
146     public void successTest() throws IOException {
147
148         /*
149          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
150          * to be pulled from the queue
151          */
152         for (TopicSink sink : noopTopics) {
153             assertTrue(sink.start());
154             sink.register(this);
155         }
156
157         /*
158          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
159          * through the rules
160          */
161         sendEvent(pair.first);
162
163         kieSession.fireUntilHalt();
164
165         // allow object clean-up
166         kieSession.fireAllRules();
167
168         /*
169          * The only fact in memory should be Params
170          */
171         assertEquals(1, kieSession.getFactCount());
172
173         /*
174          * Print what's left in memory
175          */
176         dumpFacts(kieSession);
177     }
178
179     @Test
180     public void nullRequestTest() throws IOException {
181
182         /*
183          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
184          * to be pulled from the queue
185          */
186         for (TopicSink sink : noopTopics) {
187             assertTrue(sink.start());
188             sink.register(this);
189         }
190
191         /*
192          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
193          * through the rules
194          */
195
196         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
197         event.setClosedLoopControlName(pair.first.getControlLoop().getControlLoopName());
198         event.setRequestId(UUID.randomUUID());
199         event.setClosedLoopEventClient("DCAE.HolmesInstance");
200         event.setTargetType(ControlLoopTargetType.VM);
201         event.setTarget("vserver.vserver-name");
202         event.setFrom("DCAE");
203         event.setClosedLoopAlarmStart(Instant.now());
204         event.setAai(new HashMap<String, String>());
205         event.getAai().put("vserver.vserver-name", "nullRequest");
206         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
207         kieSession.insert(event);
208
209         kieSession.fireUntilHalt();
210
211         // allow object clean-up
212         kieSession.fireAllRules();
213
214         /*
215          * The only fact in memory should be Params
216          */
217         assertEquals(1, kieSession.getFactCount());
218
219         /*
220          * Print what's left in memory
221          */
222         dumpFacts(kieSession);
223     }
224
225     /**
226      * This method will start a kie session and instantiate the Policy Engine.
227      *
228      * @param droolsTemplate the DRL rules file
229      * @param yamlFile the yaml file containing the policies
230      * @param policyScope scope for policy
231      * @param policyName name of the policy
232      * @param policyVersion version of the policy
233      * @return the kieSession to be used to insert facts
234      * @throws IOException IO Exception
235      */
236     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
237             String policyName, String policyVersion) throws IOException {
238
239         /*
240          * Load policies from yaml
241          */
242         pair = SupportUtil.loadYaml(yamlFile);
243         assertNotNull(pair);
244         assertNotNull(pair.first);
245         assertNotNull(pair.first.getControlLoop());
246         assertNotNull(pair.first.getControlLoop().getControlLoopName());
247         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
248
249         /*
250          * Construct a kie session
251          */
252         final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
253                 pair.first.getControlLoop().getControlLoopName(),
254                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second,
255                                                                           StandardCharsets.UTF_8.name()));
256
257         /*
258          * Retrieve the Policy Engine
259          */
260
261         logger.debug("============");
262         logger.debug(URLEncoder.encode(pair.second, StandardCharsets.UTF_8.name()));
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                     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=SDNC"));
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("SDNC.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=SDNC"));
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 SdncRequest) {
331             logger.debug("\n============ SDNC 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      */
341     protected void sendEvent(ControlLoopPolicy policy) {
342         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
343         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
344         event.setRequestId(UUID.randomUUID());
345         event.setClosedLoopEventClient("DCAE.HolmesInstance");
346         event.setTargetType(ControlLoopTargetType.VM);
347         event.setTarget("vserver.vserver-name");
348         event.setFrom("DCAE");
349         event.setClosedLoopAlarmStart(Instant.now());
350         event.setAai(new HashMap<String, String>());
351         event.getAai().put("vserver.vserver-name", "TBD");
352         event.getAai().put("globalSubscriberId", "e151059a-d924-4629-845f-264db19e50b4");
353         event.getAai().put("serviceType", "siteService");
354         event.getAai().put("service-instance.service-instance-id", "service-instance-id-example-1");
355         event.getAai().put("vserver.is-closed-loop-disabled", "false");
356         event.getAai().put("vserver.prov-status", "ACTIVE");
357         event.getAai().put("bandwidth", "500");
358         event.getAai().put("bandwidth-change-time", "20190326-05:20:38:668");
359         event.getAai().put("vnfId", "vnf-id");
360         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
361         kieSession.insert(event);
362     }
363
364     /**
365      * Dumps the kie session facts.
366      *
367      * @param kieSession input session
368      */
369     public static void dumpFacts(KieSession kieSession) {
370         logger.debug("Fact Count: " + kieSession.getFactCount());
371         for (FactHandle handle : kieSession.getFactHandles()) {
372             logger.debug("FACT: " + handle);
373         }
374     }
375 }