aa447ccd0c9989f8289c02eb633fe647dc915496
[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         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
76     }
77
78     /**
79      * Setup the simulator.
80      */
81     @BeforeClass
82     public static void setUpSimulator() {
83         PolicyEngine.manager.configure(new Properties());
84         assertTrue(PolicyEngine.manager.start());
85         Properties noopSinkProperties = new Properties();
86         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
87         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
88                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
89         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
90                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
91         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
92
93         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
94                 .groupId("junit.groupId")
95                 .artifactId("junit.artifactId")
96                 .topic("POLICY-CL-MGT")
97                 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
98                 .protocolFilter(new JsonProtocolFilter())
99                 .modelClassLoaderHash(1111));
100
101         try {
102             SupportUtil.buildAaiSim();
103             SupportUtil.buildSdncSim();
104         } catch (Exception e) {
105             fail(e.getMessage());
106         }
107
108         /*
109          *
110          * Start the kie session
111          */
112         try {
113             kieSession = startSession(
114                     "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
115                     + "src/main/resources/__closedLoopControlName__.drl",
116                     "src/test/resources/yaml/policy_ControlLoop_CCVPN.yaml", "type=operational", "Connectivity Reroute",
117                     "2.0.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          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
156          * through the rules
157          */
158         sendEvent(pair.first);
159
160         kieSession.fireUntilHalt();
161         
162         // allow object clean-up
163         kieSession.fireAllRules();
164
165         /*
166          * The only fact in memory should be Params
167          */
168         assertEquals(1, kieSession.getFactCount());
169
170         /*
171          * Print what's left in memory
172          */
173         dumpFacts(kieSession);
174     }
175
176     @Test
177     public void nullRequestTest() throws IOException {
178
179         /*
180          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
181          * to be pulled from the queue
182          */
183         for (TopicSink sink : noopTopics) {
184             assertTrue(sink.start());
185             sink.register(this);
186         }
187
188         /*
189          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
190          * through the rules
191          */
192
193         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
194         event.setClosedLoopControlName(pair.first.getControlLoop().getControlLoopName());
195         event.setRequestId(UUID.randomUUID());
196         event.setClosedLoopEventClient("DCAE.HolmesInstance");
197         event.setTargetType(ControlLoopTargetType.VM);
198         event.setTarget("vserver.vserver-name");
199         event.setFrom("DCAE");
200         event.setClosedLoopAlarmStart(Instant.now());
201         event.setAai(new HashMap<String, String>());
202         event.getAai().put("vserver.vserver-name", "nullRequest");
203         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
204         kieSession.insert(event);
205
206         kieSession.fireUntilHalt();
207         
208         // allow object clean-up
209         kieSession.fireAllRules();
210
211         /*
212          * The only fact in memory should be Params
213          */
214         assertEquals(1, kieSession.getFactCount());
215
216         /*
217          * Print what's left in memory
218          */
219         dumpFacts(kieSession);
220     }
221
222     /**
223      * This method will start a kie session and instantiate the Policy Engine.
224      *
225      * @param droolsTemplate the DRL rules file
226      * @param yamlFile the yaml file containing the policies
227      * @param policyScope scope for policy
228      * @param policyName name of the policy
229      * @param policyVersion version of the policy
230      * @return the kieSession to be used to insert facts
231      * @throws IOException IO Exception
232      */
233     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
234             String policyName, String policyVersion) throws IOException {
235
236         /*
237          * Load policies from yaml
238          */
239         pair = SupportUtil.loadYaml(yamlFile);
240         assertNotNull(pair);
241         assertNotNull(pair.first);
242         assertNotNull(pair.first.getControlLoop());
243         assertNotNull(pair.first.getControlLoop().getControlLoopName());
244         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
245
246         /*
247          * Construct a kie session
248          */
249         final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
250                 pair.first.getControlLoop().getControlLoopName(),
251                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
252
253         /*
254          * Retrieve the Policy Engine
255          */
256
257         logger.debug("============");
258         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
259         logger.debug("============");
260
261         return kieSession;
262     }
263
264     /*
265      * (non-Javadoc)
266      *
267      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
268      */
269     @Override
270     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
271         /*
272          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
273          * of type active
274          */
275         Object obj = null;
276         if ("POLICY-CL-MGT".equals(topic)) {
277             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
278                     VirtualControlLoopNotification.class);
279         }
280         assertNotNull(obj);
281         if (obj instanceof VirtualControlLoopNotification) {
282             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
283             String policyName = notification.getPolicyName();
284             if (policyName.endsWith("EVENT")) {
285                 logger.debug("Rule Fired: " + notification.getPolicyName());
286                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
287             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
288                 logger.debug("Rule Fired: " + notification.getPolicyName());
289                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
290                 assertNotNull(notification.getMessage());
291                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
292             } else if (policyName.endsWith("GUARD.RESPONSE")) {
293                 logger.debug("Rule Fired: " + notification.getPolicyName());
294                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
295                 assertNotNull(notification.getMessage());
296                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
297             } else if (policyName.endsWith("GUARD_PERMITTED")) {
298                 logger.debug("Rule Fired: " + notification.getPolicyName());
299                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
300                 assertNotNull(notification.getMessage());
301                 assertTrue(notification.getMessage().startsWith("actor=SDNC"));
302             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
303                 logger.debug("Rule Fired: " + notification.getPolicyName());
304                 kieSession.halt();
305                 logger.debug("The operation timed out");
306                 fail("Operation Timed Out");
307             } else if (policyName.endsWith("SDNC.RESPONSE")) {
308                 logger.debug("Rule Fired: " + notification.getPolicyName());
309                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
310                 assertNotNull(notification.getMessage());
311                 assertTrue(notification.getMessage().startsWith("actor=SDNC"));
312             } else if (policyName.endsWith("EVENT.MANAGER")) {
313                 logger.debug("Rule Fired: " + notification.getPolicyName());
314                 if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) {
315                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
316                 } else {
317                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
318                 }
319                 kieSession.halt();
320             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
321                 logger.debug("Rule Fired: " + notification.getPolicyName());
322                 kieSession.halt();
323                 logger.debug("The control loop timed out");
324                 fail("Control Loop Timed Out");
325             }
326         } else if (obj instanceof SdncRequest) {
327             logger.debug("\n============ SDNC received the request!!! ===========\n");
328         }
329     }
330
331     /**
332      * This method is used to simulate event messages from DCAE that start the control loop (onset
333      * message) or end the control loop (abatement message).
334      * 
335      * @param policy the controlLoopName comes from the policy
336      */
337     protected void sendEvent(ControlLoopPolicy policy) {
338         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
339         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
340         event.setRequestId(UUID.randomUUID());
341         event.setClosedLoopEventClient("DCAE.HolmesInstance");
342         event.setTargetType(ControlLoopTargetType.VM);
343         event.setTarget("vserver.vserver-name");
344         event.setFrom("DCAE");
345         event.setClosedLoopAlarmStart(Instant.now());
346         event.setAai(new HashMap<String, String>());
347         event.getAai().put("vserver.vserver-name", "TBD");
348         event.getAai().put("globalSubscriberId", "e151059a-d924-4629-845f-264db19e50b4");
349         event.getAai().put("serviceType", "SOTN");
350         event.getAai().put("service-instance.service-instance-id", "service-instance-id-example-1");
351         event.getAai().put("network-information.network-id", "id");
352         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
353         kieSession.insert(event);
354     }
355
356     /**
357      * Dumps the kie session facts.
358      * 
359      * @param kieSession input session
360      */
361     public static void dumpFacts(KieSession kieSession) {
362         logger.debug("Fact Count: " + kieSession.getFactCount());
363         for (FactHandle handle : kieSession.getFactHandles()) {
364             logger.debug("FACT: " + handle);
365         }
366     }
367 }
368