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