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