b64ec589ada8b6dfaa9540b70f2ed3c8b74a7d1d
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2018 Huawei. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ============LICENSE_END=========================================================
17  */
18
19 package org.onap.policy.template.demo;
20
21 import static org.junit.Assert.assertEquals;
22 import static org.junit.Assert.assertNotNull;
23 import static org.junit.Assert.assertTrue;
24 import static org.junit.Assert.fail;
25
26 import java.io.IOException;
27 import java.net.URLEncoder;
28 import java.time.Instant;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Properties;
32 import java.util.UUID;
33
34 import org.junit.AfterClass;
35 import org.junit.BeforeClass;
36 import org.junit.Test;
37 import org.kie.api.runtime.KieSession;
38 import org.kie.api.runtime.rule.FactHandle;
39 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
40 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
41 import org.onap.policy.common.endpoints.event.comm.TopicListener;
42 import org.onap.policy.common.endpoints.event.comm.TopicSink;
43 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
44 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
45 import org.onap.policy.controlloop.ControlLoopEventStatus;
46 import org.onap.policy.controlloop.ControlLoopNotificationType;
47 import org.onap.policy.controlloop.ControlLoopTargetType;
48 import org.onap.policy.controlloop.VirtualControlLoopEvent;
49 import org.onap.policy.controlloop.VirtualControlLoopNotification;
50 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
51 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
52 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
53 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
54 import org.onap.policy.drools.system.PolicyController;
55 import org.onap.policy.drools.system.PolicyEngine;
56 import org.onap.policy.drools.utils.logging.LoggerUtil;
57 import org.onap.policy.sdnc.SdncRequest;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60
61 public class CcvpnControlLoopTest implements TopicListener {
62
63     private static final Logger logger = LoggerFactory.getLogger(CcvpnControlLoopTest.class);
64
65     private static List<? extends TopicSink> noopTopics;
66
67     private static KieSession kieSession;
68     private static SupportUtil.Pair<ControlLoopPolicy, String> pair;
69
70     static {
71         /* Set environment properties */
72         SupportUtil.setAaiProps();
73         SupportUtil.setSdncProps();
74         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
75     }
76
77     /**
78      * Setup the simulator.
79      */
80     @BeforeClass
81     public static void setUpSimulator() {
82         PolicyEngine.manager.configure(new Properties());
83         assertTrue(PolicyEngine.manager.start());
84         Properties noopSinkProperties = new Properties();
85         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
86         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
87                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
88         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
89                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
90         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
91
92         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
93                 .groupId("junit.groupId")
94                 .artifactId("junit.artifactId")
95                 .topic("POLICY-CL-MGT")
96                 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
97                 .protocolFilter(new JsonProtocolFilter())
98                 .customGsonCoder(null)
99                 .customJacksonCoder(null)
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.yaml", "type=operational", "Connectivity Reroute",
118                     "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, "UTF-8"));
253
254         /*
255          * Retrieve the Policy Engine
256          */
257
258         logger.debug("============");
259         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
260         logger.debug("============");
261
262         return kieSession;
263     }
264
265     /*
266      * (non-Javadoc)
267      *
268      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
269      */
270     @Override
271     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
272         /*
273          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
274          * of type active
275          */
276         Object obj = null;
277         if ("POLICY-CL-MGT".equals(topic)) {
278             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
279                     VirtualControlLoopNotification.class);
280         }
281         assertNotNull(obj);
282         if (obj instanceof VirtualControlLoopNotification) {
283             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
284             String policyName = notification.getPolicyName();
285             if (policyName.endsWith("EVENT")) {
286                 logger.debug("Rule Fired: " + notification.getPolicyName());
287                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
288             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
289                 logger.debug("Rule Fired: " + notification.getPolicyName());
290                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
291                 assertNotNull(notification.getMessage());
292                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
293             } else if (policyName.endsWith("GUARD.RESPONSE")) {
294                 logger.debug("Rule Fired: " + notification.getPolicyName());
295                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
296                 assertNotNull(notification.getMessage());
297                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
298             } else if (policyName.endsWith("GUARD_PERMITTED")) {
299                 logger.debug("Rule Fired: " + notification.getPolicyName());
300                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
301                 assertNotNull(notification.getMessage());
302                 assertTrue(notification.getMessage().startsWith("actor=SDNC"));
303             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
304                 logger.debug("Rule Fired: " + notification.getPolicyName());
305                 kieSession.halt();
306                 logger.debug("The operation timed out");
307                 fail("Operation Timed Out");
308             } else if (policyName.endsWith("SDNC.RESPONSE")) {
309                 logger.debug("Rule Fired: " + notification.getPolicyName());
310                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
311                 assertNotNull(notification.getMessage());
312                 assertTrue(notification.getMessage().startsWith("actor=SDNC"));
313             } else if (policyName.endsWith("EVENT.MANAGER")) {
314                 logger.debug("Rule Fired: " + notification.getPolicyName());
315                 if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) {
316                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
317                 } else {
318                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
319                 }
320                 kieSession.halt();
321             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
322                 logger.debug("Rule Fired: " + notification.getPolicyName());
323                 kieSession.halt();
324                 logger.debug("The control loop timed out");
325                 fail("Control Loop Timed Out");
326             }
327         } else if (obj instanceof SdncRequest) {
328             logger.debug("\n============ SDNC received the request!!! ===========\n");
329         }
330     }
331
332     /**
333      * This method is used to simulate event messages from DCAE that start the control loop (onset
334      * message) or end the control loop (abatement message).
335      * 
336      * @param policy the controlLoopName comes from the policy
337      */
338     protected void sendEvent(ControlLoopPolicy policy) {
339         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
340         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
341         event.setRequestId(UUID.randomUUID());
342         event.setClosedLoopEventClient("DCAE.HolmesInstance");
343         event.setTargetType(ControlLoopTargetType.VM);
344         event.setTarget("vserver.vserver-name");
345         event.setFrom("DCAE");
346         event.setClosedLoopAlarmStart(Instant.now());
347         event.setAai(new HashMap<String, String>());
348         event.getAai().put("vserver.vserver-name", "TBD");
349         event.getAai().put("globalSubscriberId", "e151059a-d924-4629-845f-264db19e50b4");
350         event.getAai().put("serviceType", "SOTN");
351         event.getAai().put("service-instance.service-instance-id", "service-instance-id-example-1");
352         event.getAai().put("network-information.network-id", "id");
353         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
354         kieSession.insert(event);
355     }
356
357     /**
358      * Dumps the kie session facts.
359      * 
360      * @param kieSession input session
361      */
362     public static void dumpFacts(KieSession kieSession) {
363         logger.debug("Fact Count: " + kieSession.getFactCount());
364         for (FactHandle handle : kieSession.getFactHandles()) {
365             logger.debug("FACT: " + handle);
366         }
367     }
368 }
369