564b12a476c5703af6ba692b94eb46773932b1c4
[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         // 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 namedQueryFailTest() {
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          * Create a unique requestId
192          */
193         requestId = UUID.randomUUID();
194
195         /*
196          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
197          * through the rules
198          */
199         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error");
200
201         kieSession.fireUntilHalt();
202         
203         // allow object clean-up
204         kieSession.fireAllRules();
205
206         /*
207          * The only fact in memory should be Params
208          */
209         assertEquals(1, kieSession.getFactCount());
210
211         /*
212          * Print what's left in memory
213          */
214         dumpFacts(kieSession);
215     }
216
217     @Test
218     public void aaiGetFailTest() {
219
220         /*
221          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
222          * to be pulled from the queue
223          */
224         for (TopicSink sink : noopTopics) {
225             assertTrue(sink.start());
226             sink.register(this);
227         }
228
229         /*
230          * Create a unique requestId
231          */
232         requestId = UUID.randomUUID();
233
234         /*
235          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
236          * through the rules
237          */
238         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail");
239
240         try {
241             kieSession.fireUntilHalt();
242             
243             // allow object clean-up
244             kieSession.fireAllRules();
245             
246         } catch (Exception e) {
247             e.printStackTrace();
248             logger.warn(e.toString());
249             fail(e.getMessage());
250         }
251
252
253         /*
254          * The only fact in memory should be Params
255          */
256         assertEquals(1, kieSession.getFactCount());
257
258         /*
259          * Print what's left in memory
260          */
261         dumpFacts(kieSession);
262     }
263
264     /**
265      * This method will start a kie session and instantiate the Policy Engine.
266      * 
267      * @param droolsTemplate the DRL rules file
268      * @param yamlFile the yaml file containing the policies
269      * @param policyScope scope for policy
270      * @param policyName name of the policy
271      * @param policyVersion version of the policy
272      * @return the kieSession to be used to insert facts
273      * @throws IOException IO Exception
274      */
275     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
276             String policyName, String policyVersion) throws IOException {
277
278         /*
279          * Load policies from yaml
280          */
281         pair = Util.loadYaml(yamlFile);
282         assertNotNull(pair);
283         assertNotNull(pair.first);
284         assertNotNull(pair.first.getControlLoop());
285         assertNotNull(pair.first.getControlLoop().getControlLoopName());
286         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
287
288         /*
289          * Construct a kie session
290          */
291         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
292                 pair.first.getControlLoop().getControlLoopName(),
293                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
294
295         /*
296          * Retrieve the Policy Engine
297          */
298
299         logger.debug("============");
300         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
301         logger.debug("============");
302
303         return kieSession;
304     }
305
306     /*
307      * (non-Javadoc)
308      * 
309      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
310      */
311     @Override
312     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
313         /*
314          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
315          * of type active
316          */
317         Object obj = null;
318         if ("POLICY-CL-MGT".equals(topic)) {
319             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
320                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
321         }
322         assertNotNull(obj);
323         if (obj instanceof VirtualControlLoopNotification) {
324             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
325             String policyName = notification.getPolicyName();
326             if (policyName.endsWith("EVENT")) {
327                 logger.debug("Rule Fired: " + notification.getPolicyName());
328                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
329             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
330                 logger.debug("Rule Fired: " + notification.getPolicyName());
331                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
332                 assertNotNull(notification.getMessage());
333                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
334             } else if (policyName.endsWith("GUARD.RESPONSE")) {
335                 logger.debug("Rule Fired: " + notification.getPolicyName());
336                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
337                 assertNotNull(notification.getMessage());
338                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
339             } else if (policyName.endsWith("GUARD_PERMITTED")) {
340                 logger.debug("Rule Fired: " + notification.getPolicyName());
341                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
342                 assertNotNull(notification.getMessage());
343                 assertTrue(notification.getMessage().startsWith("actor=SO"));
344             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
345                 logger.debug("Rule Fired: " + notification.getPolicyName());
346                 kieSession.halt();
347                 logger.debug("The operation timed out");
348                 fail("Operation Timed Out");
349             } else if (policyName.endsWith("SO.RESPONSE")) {
350                 logger.debug("Rule Fired: " + notification.getPolicyName());
351                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
352                 assertNotNull(notification.getMessage());
353                 assertTrue(notification.getMessage().startsWith("actor=SO"));
354             } else if (policyName.endsWith("EVENT.MANAGER")) {
355                 logger.debug("Rule Fired: " + notification.getPolicyName());
356                 if ("error".equals(notification.getAai().get("vserver.vserver-name"))) {
357                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
358                 } else if ("getFail".equals(notification.getAai().get("vserver.vserver-name"))) {
359                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
360                 } else {
361                     assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
362                 }
363                 kieSession.halt();
364             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
365                 logger.debug("Rule Fired: " + notification.getPolicyName());
366                 kieSession.halt();
367                 logger.debug("The control loop timed out");
368                 fail("Control Loop Timed Out");
369             }
370         } else if (obj instanceof SORequest) {
371             logger.debug("\n============ SO received the request!!! ===========\n");
372         }
373     }
374
375     /**
376      * This method is used to simulate event messages from DCAE that start the control loop (onset
377      * message) or end the control loop (abatement message).
378      * 
379      * @param policy the controlLoopName comes from the policy
380      * @param requestID the requestId for this event
381      * @param status could be onset or abated
382      */
383     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
384         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
385         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
386         event.setRequestId(requestId);
387         event.setTarget("vserver.vserver-name");
388         event.setClosedLoopAlarmStart(Instant.now());
389         event.setAai(new HashMap<>());
390         event.getAai().put("vserver.vserver-name", "dfw1lb01lb01");
391         event.getAai().put("vserver.is-closed-loop-disabled", "false");
392         event.getAai().put("vserver.prov-status", "ACTIVE");
393         event.setClosedLoopEventStatus(status);
394         kieSession.insert(event);
395     }
396
397     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
398             String vserverName) {
399         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
400         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
401         event.setRequestId(requestId);
402         event.setTarget("vserver.vserver-name");
403         event.setClosedLoopAlarmStart(Instant.now());
404         event.setAai(new HashMap<>());
405         event.getAai().put("vserver.vserver-name", vserverName);
406         event.setClosedLoopEventStatus(status);
407         kieSession.insert(event);
408     }
409
410     /**
411      * This method will dump all the facts in the working memory.
412      * 
413      * @param kieSession the session containing the facts
414      */
415     public void dumpFacts(KieSession kieSession) {
416         logger.debug("Fact Count: {}", kieSession.getFactCount());
417         for (FactHandle handle : kieSession.getFactHandles()) {
418             logger.debug("FACT: {}", handle);
419         }
420     }
421 }