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