b5b7a485809b66a8de9a72d767efc70c6c53e17f
[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.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.so.SORequest;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 public class VdnsControlLoopTest implements TopicListener {
63
64     private static final Logger logger = LoggerFactory.getLogger(VdnsControlLoopTest.class);
65
66     private static List<? extends TopicSink> noopTopics;
67
68     private static KieSession kieSession;
69     private static Util.Pair<ControlLoopPolicy, String> pair;
70     private UUID requestId;
71
72     static {
73         /* Set environment properties */
74         Util.setAaiProps();
75         Util.setSoProps();
76         Util.setGuardProps();
77         Util.setPuProp();
78         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
79     }
80
81     /**
82      * Setup the simulator.
83      */
84     @BeforeClass
85     public static void setUpSimulator() {
86         PolicyEngine.manager.configure(new Properties());
87         assertTrue(PolicyEngine.manager.start());
88         Properties noopSinkProperties = new Properties();
89         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
90         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
91                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
92         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
93                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
94         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
95
96         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
97                 .groupId("junit.groupId")
98                 .artifactId("junit.artifactId")
99                 .topic("POLICY-CL-MGT")
100                 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
101                 .protocolFilter(new JsonProtocolFilter())
102                 .customGsonCoder(null)
103                 .customJacksonCoder(null)
104                 .modelClassLoaderHash(1111));
105
106         try {
107             Util.buildAaiSim();
108             Util.buildSoSim();
109             Util.buildGuardSim();
110         } catch (Exception e) {
111             fail(e.getMessage());
112         }
113
114         /*
115          * Start the kie session
116          */
117         try {
118             kieSession = startSession(
119                     "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
120                     + "src/main/resources/__closedLoopControlName__.drl",
121                     "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml", "type=operational", "CL_vDNS", "v2.0");
122         } catch (IOException e) {
123             e.printStackTrace();
124             logger.debug("Could not create kieSession");
125             fail("Could not create kieSession");
126         }
127     }
128
129     /**
130      * Tear down the simulator.
131      */
132     @AfterClass
133     public static void tearDownSimulator() {
134
135         /*
136          * Gracefully shut down the kie session
137          */
138         kieSession.dispose();
139
140         PolicyEngine.manager.stop();
141         HttpServletServer.factory.destroy();
142         PolicyController.factory.shutdown();
143         TopicEndpoint.manager.shutdown();
144     }
145
146     @Test
147     public void successTest() {
148
149         /*
150          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
151          * to be pulled from the queue
152          */
153         for (TopicSink sink : noopTopics) {
154             assertTrue(sink.start());
155             sink.register(this);
156         }
157
158         /*
159          * Create a unique requestId
160          */
161         requestId = UUID.randomUUID();
162
163         /*
164          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
165          * through the rules
166          */
167         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
168
169         kieSession.fireUntilHalt();
170         
171         // allow object clean-up
172         kieSession.fireAllRules();
173
174         /*
175          * The only fact in memory should be Params
176          */
177         assertEquals(1, kieSession.getFactCount());
178
179         /*
180          * Print what's left in memory
181          */
182         dumpFacts(kieSession);
183     }
184
185     @Test
186     public void namedQueryFailTest() {
187
188         /*
189          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
190          * to be pulled from the queue
191          */
192         for (TopicSink sink : noopTopics) {
193             assertTrue(sink.start());
194             sink.register(this);
195         }
196
197         /*
198          * Create a unique requestId
199          */
200         requestId = UUID.randomUUID();
201
202         /*
203          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
204          * through the rules
205          */
206         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error");
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     @Test
225     public void aaiGetFailTest() {
226
227         /*
228          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
229          * to be pulled from the queue
230          */
231         for (TopicSink sink : noopTopics) {
232             assertTrue(sink.start());
233             sink.register(this);
234         }
235
236         /*
237          * Create a unique requestId
238          */
239         requestId = UUID.randomUUID();
240
241         /*
242          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
243          * through the rules
244          */
245         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail");
246
247         try {
248             kieSession.fireUntilHalt();
249             
250             // allow object clean-up
251             kieSession.fireAllRules();
252             
253         } catch (Exception e) {
254             e.printStackTrace();
255             logger.warn(e.toString());
256             fail(e.getMessage());
257         }
258
259
260         /*
261          * The only fact in memory should be Params
262          */
263         assertEquals(1, kieSession.getFactCount());
264
265         /*
266          * Print what's left in memory
267          */
268         dumpFacts(kieSession);
269     }
270
271     /**
272      * This method will start a kie session and instantiate the Policy Engine.
273      * 
274      * @param droolsTemplate the DRL rules file
275      * @param yamlFile the yaml file containing the policies
276      * @param policyScope scope for policy
277      * @param policyName name of the policy
278      * @param policyVersion version of the policy
279      * @return the kieSession to be used to insert facts
280      * @throws IOException IO Exception
281      */
282     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
283             String policyName, String policyVersion) throws IOException {
284
285         /*
286          * Load policies from yaml
287          */
288         pair = Util.loadYaml(yamlFile);
289         assertNotNull(pair);
290         assertNotNull(pair.first);
291         assertNotNull(pair.first.getControlLoop());
292         assertNotNull(pair.first.getControlLoop().getControlLoopName());
293         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
294
295         /*
296          * Construct a kie session
297          */
298         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
299                 pair.first.getControlLoop().getControlLoopName(),
300                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
301
302         /*
303          * Retrieve the Policy Engine
304          */
305
306         logger.debug("============");
307         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
308         logger.debug("============");
309
310         return kieSession;
311     }
312
313     /*
314      * (non-Javadoc)
315      * 
316      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
317      */
318     @Override
319     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
320         /*
321          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
322          * of type active
323          */
324         Object obj = null;
325         if ("POLICY-CL-MGT".equals(topic)) {
326             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
327                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
328         }
329         assertNotNull(obj);
330         if (obj instanceof VirtualControlLoopNotification) {
331             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
332             String policyName = notification.getPolicyName();
333             if (policyName.endsWith("EVENT")) {
334                 logger.debug("Rule Fired: " + notification.getPolicyName());
335                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
336             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
337                 logger.debug("Rule Fired: " + notification.getPolicyName());
338                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
339                 assertNotNull(notification.getMessage());
340                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
341             } else if (policyName.endsWith("GUARD.RESPONSE")) {
342                 logger.debug("Rule Fired: " + notification.getPolicyName());
343                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
344                 assertNotNull(notification.getMessage());
345                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
346             } else if (policyName.endsWith("GUARD_PERMITTED")) {
347                 logger.debug("Rule Fired: " + notification.getPolicyName());
348                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
349                 assertNotNull(notification.getMessage());
350                 assertTrue(notification.getMessage().startsWith("actor=SO"));
351             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
352                 logger.debug("Rule Fired: " + notification.getPolicyName());
353                 kieSession.halt();
354                 logger.debug("The operation timed out");
355                 fail("Operation Timed Out");
356             } else if (policyName.endsWith("SO.RESPONSE")) {
357                 logger.debug("Rule Fired: " + notification.getPolicyName());
358                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
359                 assertNotNull(notification.getMessage());
360                 assertTrue(notification.getMessage().startsWith("actor=SO"));
361             } else if (policyName.endsWith("EVENT.MANAGER")) {
362                 logger.debug("Rule Fired: " + notification.getPolicyName());
363                 if ("error".equals(notification.getAai().get("vserver.vserver-name"))) {
364                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
365                 } else if ("getFail".equals(notification.getAai().get("vserver.vserver-name"))) {
366                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
367                 } else {
368                     assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
369                 }
370                 kieSession.halt();
371             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
372                 logger.debug("Rule Fired: " + notification.getPolicyName());
373                 kieSession.halt();
374                 logger.debug("The control loop timed out");
375                 fail("Control Loop Timed Out");
376             }
377         } else if (obj instanceof SORequest) {
378             logger.debug("\n============ SO received the request!!! ===========\n");
379         }
380     }
381
382     /**
383      * This method is used to simulate event messages from DCAE that start the control loop (onset
384      * message) or end the control loop (abatement message).
385      * 
386      * @param policy the controlLoopName comes from the policy
387      * @param requestId the requestId for this event
388      * @param status could be onset or abated
389      */
390     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
391         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
392         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
393         event.setRequestId(requestId);
394         event.setTarget("vserver.vserver-name");
395         event.setClosedLoopAlarmStart(Instant.now());
396         event.setAai(new HashMap<>());
397         event.getAai().put("vserver.vserver-name", "dfw1lb01lb01");
398         event.getAai().put("vserver.is-closed-loop-disabled", "false");
399         event.getAai().put("vserver.prov-status", "ACTIVE");
400         event.setClosedLoopEventStatus(status);
401         kieSession.insert(event);
402     }
403
404     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
405             String vserverName) {
406         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
407         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
408         event.setRequestId(requestId);
409         event.setTarget("vserver.vserver-name");
410         event.setClosedLoopAlarmStart(Instant.now());
411         event.setAai(new HashMap<>());
412         event.getAai().put("vserver.vserver-name", vserverName);
413         event.setClosedLoopEventStatus(status);
414         kieSession.insert(event);
415     }
416
417     /**
418      * This method will dump all the facts in the working memory.
419      * 
420      * @param kieSession the session containing the facts
421      */
422     public void dumpFacts(KieSession kieSession) {
423         logger.debug("Fact Count: {}", kieSession.getFactCount());
424         for (FactHandle handle : kieSession.getFactHandles()) {
425             logger.debug("FACT: {}", handle);
426         }
427     }
428 }