c546248f2682706c47dba40cbb6876f1093455c6
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2018 Huawei. 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.time.Instant;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Properties;
33 import java.util.UUID;
34
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.TopicEndpoint;
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.HttpServletServer;
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 CcvpnControlLoopTest implements TopicListener {
63
64     private static final Logger logger = LoggerFactory.getLogger(CcvpnControlLoopTest.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 = 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             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.yaml", "type=operational", "Connectivity Reroute",
119                     "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         HttpServletServer.factory.destroy();
140         PolicyController.factory.shutdown();
141         TopicEndpoint.manager.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, "UTF-8"));
254
255         /*
256          * Retrieve the Policy Engine
257          */
258
259         logger.debug("============");
260         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
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", "SOTN");
352         event.getAai().put("service-instance.service-instance-id", "service-instance-id-example-1");
353         event.getAai().put("network-information.network-id", "id");
354         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
355         kieSession.insert(event);
356     }
357
358     /**
359      * Dumps the kie session facts.
360      *
361      * @param kieSession input session
362      */
363     public static void dumpFacts(KieSession kieSession) {
364         logger.debug("Fact Count: " + kieSession.getFactCount());
365         for (FactHandle handle : kieSession.getFactHandles()) {
366             logger.debug("FACT: " + handle);
367         }
368     }
369 }
370