d1fb29e0a7183adbda2d0e06c189112fbf5f5e28
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.template.demo;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
27
28 import java.io.IOException;
29 import java.net.URLEncoder;
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.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.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.so.SORequest;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60
61 public class VdnsControlLoopTest implements TopicListener {
62
63     private static final Logger logger = LoggerFactory.getLogger(VdnsControlLoopTest.class);
64
65     private static List<? extends TopicSink> noopTopics;
66
67     private static KieSession kieSession;
68     private static Util.Pair<ControlLoopPolicy, String> pair;
69     private UUID requestId;
70
71     static {
72         /* Set environment properties */
73         Util.setAaiProps();
74         Util.setSoProps();
75         Util.setGuardProps();
76         Util.setPuProp();
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("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
96                 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
97                 1111);
98
99         try {
100             Util.buildAaiSim();
101             Util.buildSoSim();
102             Util.buildGuardSim();
103         } catch (Exception e) {
104             fail(e.getMessage());
105         }
106
107         /*
108          * Start the kie session
109          */
110         try {
111             kieSession = startSession(
112                     "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
113                     + "src/main/resources/__closedLoopControlName__.drl",
114                     "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml", "type=operational", "CL_vDNS", "v2.0");
115         } catch (IOException e) {
116             e.printStackTrace();
117             logger.debug("Could not create kieSession");
118             fail("Could not create kieSession");
119         }
120     }
121
122     /**
123      * Tear down the simulator.
124      */
125     @AfterClass
126     public static void tearDownSimulator() {
127
128         /*
129          * Gracefully shut down the kie session
130          */
131         kieSession.dispose();
132
133         PolicyEngine.manager.stop();
134         HttpServletServer.factory.destroy();
135         PolicyController.factory.shutdown();
136         TopicEndpoint.manager.shutdown();
137     }
138
139     @Test
140     public void successTest() {
141
142         /*
143          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
144          * to be pulled from the queue
145          */
146         for (TopicSink sink : noopTopics) {
147             assertTrue(sink.start());
148             sink.register(this);
149         }
150
151         /*
152          * Create a unique requestId
153          */
154         requestId = UUID.randomUUID();
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, requestId, ControlLoopEventStatus.ONSET);
161
162         kieSession.fireUntilHalt();
163
164         /*
165          * The only fact in memory should be Params
166          */
167         assertEquals(1, kieSession.getFactCount());
168
169         /*
170          * Print what's left in memory
171          */
172         dumpFacts(kieSession);
173     }
174
175     @Test
176     public void namedQueryFailTest() {
177
178         /*
179          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
180          * to be pulled from the queue
181          */
182         for (TopicSink sink : noopTopics) {
183             assertTrue(sink.start());
184             sink.register(this);
185         }
186
187         /*
188          * Create a unique requestId
189          */
190         requestId = UUID.randomUUID();
191
192         /*
193          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
194          * through the rules
195          */
196         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error");
197
198         kieSession.fireUntilHalt();
199
200         /*
201          * The only fact in memory should be Params
202          */
203         assertEquals(1, kieSession.getFactCount());
204
205         /*
206          * Print what's left in memory
207          */
208         dumpFacts(kieSession);
209     }
210
211     @Test
212     public void aaiGetFailTest() {
213
214         /*
215          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
216          * to be pulled from the queue
217          */
218         for (TopicSink sink : noopTopics) {
219             assertTrue(sink.start());
220             sink.register(this);
221         }
222
223         /*
224          * Create a unique requestId
225          */
226         requestId = UUID.randomUUID();
227
228         /*
229          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
230          * through the rules
231          */
232         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail");
233
234         try {
235             kieSession.fireUntilHalt();
236         } catch (Exception e) {
237             e.printStackTrace();
238             logger.warn(e.toString());
239             fail(e.getMessage());
240         }
241
242
243         /*
244          * The only fact in memory should be Params
245          */
246         assertEquals(1, kieSession.getFactCount());
247
248         /*
249          * Print what's left in memory
250          */
251         dumpFacts(kieSession);
252     }
253
254     /**
255      * This method will start a kie session and instantiate the Policy Engine.
256      * 
257      * @param droolsTemplate the DRL rules file
258      * @param yamlFile the yaml file containing the policies
259      * @param policyScope scope for policy
260      * @param policyName name of the policy
261      * @param policyVersion version of the policy
262      * @return the kieSession to be used to insert facts
263      * @throws IOException IO Exception
264      */
265     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
266             String policyName, String policyVersion) throws IOException {
267
268         /*
269          * Load policies from yaml
270          */
271         pair = Util.loadYaml(yamlFile);
272         assertNotNull(pair);
273         assertNotNull(pair.first);
274         assertNotNull(pair.first.getControlLoop());
275         assertNotNull(pair.first.getControlLoop().getControlLoopName());
276         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
277
278         /*
279          * Construct a kie session
280          */
281         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
282                 pair.first.getControlLoop().getControlLoopName(),
283                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
284
285         /*
286          * Retrieve the Policy Engine
287          */
288
289         logger.debug("============");
290         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
291         logger.debug("============");
292
293         return kieSession;
294     }
295
296     /*
297      * (non-Javadoc)
298      * 
299      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
300      */
301     @Override
302     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
303         /*
304          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
305          * of type active
306          */
307         Object obj = null;
308         if ("POLICY-CL-MGT".equals(topic)) {
309             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
310                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
311         }
312         assertNotNull(obj);
313         if (obj instanceof VirtualControlLoopNotification) {
314             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
315             String policyName = notification.getPolicyName();
316             if (policyName.endsWith("EVENT")) {
317                 logger.debug("Rule Fired: " + notification.getPolicyName());
318                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
319             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
320                 logger.debug("Rule Fired: " + notification.getPolicyName());
321                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
322                 assertNotNull(notification.getMessage());
323                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
324             } else if (policyName.endsWith("GUARD.RESPONSE")) {
325                 logger.debug("Rule Fired: " + notification.getPolicyName());
326                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
327                 assertNotNull(notification.getMessage());
328                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
329             } else if (policyName.endsWith("GUARD_PERMITTED")) {
330                 logger.debug("Rule Fired: " + notification.getPolicyName());
331                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
332                 assertNotNull(notification.getMessage());
333                 assertTrue(notification.getMessage().startsWith("actor=SO"));
334             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
335                 logger.debug("Rule Fired: " + notification.getPolicyName());
336                 kieSession.halt();
337                 logger.debug("The operation timed out");
338                 fail("Operation Timed Out");
339             } else if (policyName.endsWith("SO.RESPONSE")) {
340                 logger.debug("Rule Fired: " + notification.getPolicyName());
341                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
342                 assertNotNull(notification.getMessage());
343                 assertTrue(notification.getMessage().startsWith("actor=SO"));
344             } else if (policyName.endsWith("EVENT.MANAGER")) {
345                 logger.debug("Rule Fired: " + notification.getPolicyName());
346                 if ("error".equals(notification.getAai().get("vserver.vserver-name"))) {
347                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
348                 } else if ("getFail".equals(notification.getAai().get("vserver.vserver-name"))) {
349                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
350                 } else {
351                     assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
352                 }
353                 kieSession.halt();
354             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
355                 logger.debug("Rule Fired: " + notification.getPolicyName());
356                 kieSession.halt();
357                 logger.debug("The control loop timed out");
358                 fail("Control Loop Timed Out");
359             }
360         } else if (obj instanceof SORequest) {
361             logger.debug("\n============ SO received the request!!! ===========\n");
362         }
363     }
364
365     /**
366      * This method is used to simulate event messages from DCAE that start the control loop (onset
367      * message) or end the control loop (abatement message).
368      * 
369      * @param policy the controlLoopName comes from the policy
370      * @param requestID the requestId for this event
371      * @param status could be onset or abated
372      */
373     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
374         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
375         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
376         event.setRequestId(requestId);
377         event.setTarget("vserver.vserver-name");
378         event.setClosedLoopAlarmStart(Instant.now());
379         event.setAai(new HashMap<>());
380         event.getAai().put("vserver.vserver-name", "dfw1lb01lb01");
381         event.getAai().put("vserver.is-closed-loop-disabled", "false");
382         event.getAai().put("vserver.prov-status", "ACTIVE");
383         event.setClosedLoopEventStatus(status);
384         kieSession.insert(event);
385     }
386
387     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
388             String vserverName) {
389         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
390         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
391         event.setRequestId(requestId);
392         event.setTarget("vserver.vserver-name");
393         event.setClosedLoopAlarmStart(Instant.now());
394         event.setAai(new HashMap<>());
395         event.getAai().put("vserver.vserver-name", vserverName);
396         event.setClosedLoopEventStatus(status);
397         kieSession.insert(event);
398     }
399
400     /**
401      * This method will dump all the facts in the working memory.
402      * 
403      * @param kieSession the session containing the facts
404      */
405     public void dumpFacts(KieSession kieSession) {
406         logger.debug("Fact Count: {}", kieSession.getFactCount());
407         for (FactHandle handle : kieSession.getFactHandles()) {
408             logger.debug("FACT: {}", handle);
409         }
410     }
411 }