c64764baf353195894d6034d3ab3ab38be1c3c14
[policy/drools-applications.git] / controlloop / templates / template.demo / src / test / java / org / onap / policy / template / demo / VDNSControlLoopTest.java
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.PolicyEngine;
55 import org.onap.policy.so.SORequest;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 public class VDNSControlLoopTest implements TopicListener {
60
61     private static final Logger logger = LoggerFactory.getLogger(VDNSControlLoopTest.class);
62     
63     private static List<? extends TopicSink> noopTopics;
64     
65     private KieSession kieSession;
66     private Util.Pair<ControlLoopPolicy, String> pair;
67     private UUID requestID;
68     
69     static {
70         /* Set environment properties */
71         Util.setAAIProps();
72         Util.setSOProps();
73         Util.setGuardProps();
74         Util.setPUProp();
75     }
76     
77         @BeforeClass
78         public static void setUpSimulator() {
79                 PolicyEngine.manager.configure(new Properties());
80         assertTrue(PolicyEngine.manager.start());
81         Properties noopSinkProperties = new Properties();
82         noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
83         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", "org.onap.policy.controlloop.VirtualControlLoopNotification");
84         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", "org.onap.policy.controlloop.util.Serialization,gsonPretty");
85         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
86         
87         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, 1111);
88
89                 try {
90                         Util.buildAaiSim();
91                         Util.buildSoSim();
92                         Util.buildGuardSim();
93                 } catch (Exception e) {
94                         fail(e.getMessage());
95                 }
96         }
97
98         @AfterClass
99         public static void tearDownSimulator() {
100                 HttpServletServer.factory.destroy();
101                 PolicyEngine.manager.shutdown();
102         }
103
104     @Test
105     public void successTest() {
106         
107         /*
108          * Start the kie session
109          */
110         try {
111             kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", 
112                         "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml",
113                         "type=operational", 
114                         "CL_vDNS", 
115                         "v2.0");
116         } catch (IOException e) {
117             e.printStackTrace();
118             logger.debug("Could not create kieSession");
119             fail("Could not create kieSession");
120         }
121         
122         /*
123          * Allows the PolicyEngine to callback to this object to
124          * notify that there is an event ready to be pulled 
125          * from the queue
126          */
127         for (TopicSink sink : noopTopics) {
128             assertTrue(sink.start());
129             sink.register(this);
130         }
131         
132         /*
133          * Create a unique requestId
134          */
135         requestID = UUID.randomUUID();
136         
137         /* 
138          * Simulate an onset event the policy engine will 
139          * receive from DCAE to kick off processing through
140          * the rules
141          */
142         sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
143         
144         kieSession.fireUntilHalt();
145         
146         /*
147          * The only fact in memory should be Params
148          */
149         assertEquals(1, kieSession.getFactCount());
150         
151         /*
152          * Print what's left in memory
153          */
154         dumpFacts(kieSession);
155         
156         /*
157          * Gracefully shut down the kie session
158          */
159         kieSession.dispose();
160     }
161     
162     /**
163      * This method will start a kie session and instantiate 
164      * the Policy Engine.
165      * 
166      * @param droolsTemplate
167      *          the DRL rules file
168      * @param yamlFile
169      *          the yaml file containing the policies
170      * @param policyScope
171      *          scope for policy
172      * @param policyName
173      *          name of the policy
174      * @param policyVersion
175      *          version of the policy          
176      * @return the kieSession to be used to insert facts 
177      * @throws IOException
178      */
179     private KieSession startSession(String droolsTemplate, 
180             String yamlFile, 
181             String policyScope, 
182             String policyName, 
183             String policyVersion) throws IOException {
184         
185         /*
186          * Load policies from yaml
187          */
188         pair = Util.loadYaml(yamlFile);
189         assertNotNull(pair);
190         assertNotNull(pair.a);
191         assertNotNull(pair.a.getControlLoop());
192         assertNotNull(pair.a.getControlLoop().getControlLoopName());
193         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
194         
195         /* 
196          * Construct a kie session
197          */
198         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
199                 pair.a.getControlLoop().getControlLoopName(), 
200                 policyScope, 
201                 policyName, 
202                 policyVersion, 
203                 URLEncoder.encode(pair.b, "UTF-8"));
204         
205         /*
206          * Retrieve the Policy Engine
207          */
208         
209         logger.debug("============");
210         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
211         logger.debug("============");
212         
213         return kieSession;
214     }
215     
216     /*
217      * (non-Javadoc)
218      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
219      */
220     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
221         /*
222          * Pull the object that was sent out to DMAAP and make
223          * sure it is a ControlLoopNoticiation of type active
224          */
225         Object obj = null;
226         if ("POLICY-CL-MGT".equals(topic)) {
227                 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
228         }
229         assertNotNull(obj);
230         if (obj instanceof VirtualControlLoopNotification) {
231             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
232             String policyName = notification.policyName;
233             if (policyName.endsWith("EVENT")) {
234                 logger.debug("Rule Fired: " + notification.policyName);
235                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
236             }
237             else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
238                 logger.debug("Rule Fired: " + notification.policyName);
239                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
240                 assertNotNull(notification.message);
241                 assertTrue(notification.message.startsWith("Sending guard query"));
242             }
243             else if (policyName.endsWith("GUARD.RESPONSE")) {
244                 logger.debug("Rule Fired: " + notification.policyName);
245                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
246                 assertNotNull(notification.message);
247                 assertTrue(notification.message.toLowerCase().endsWith("permit"));
248             }
249             else if (policyName.endsWith("GUARD_PERMITTED")) {
250                 logger.debug("Rule Fired: " + notification.policyName);
251                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
252                 assertNotNull(notification.message);
253                 assertTrue(notification.message.startsWith("actor=SO"));
254             }
255             else if (policyName.endsWith("OPERATION.TIMEOUT")) {
256                 logger.debug("Rule Fired: " + notification.policyName);
257                 kieSession.halt();
258                 logger.debug("The operation timed out");
259                 fail("Operation Timed Out");
260             }
261             else if (policyName.endsWith("SO.RESPONSE")) {
262                 logger.debug("Rule Fired: " + notification.policyName);
263                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
264                 assertNotNull(notification.message);
265                 assertTrue(notification.message.startsWith("actor=SO"));
266             }
267             else if (policyName.endsWith("EVENT.MANAGER")) {
268                 logger.debug("Rule Fired: " + notification.policyName);
269                 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
270                 kieSession.halt();
271             }
272             else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
273                 logger.debug("Rule Fired: " + notification.policyName);
274                 kieSession.halt();
275                 logger.debug("The control loop timed out");
276                 fail("Control Loop Timed Out");
277             }
278         }
279         else if (obj instanceof SORequest) {
280             logger.debug("\n============ SO received the request!!! ===========\n");
281         }        
282     }
283     
284     /**
285      * This method is used to simulate event messages from DCAE
286      * that start the control loop (onset message) or end the
287      * control loop (abatement message).
288      * 
289      * @param policy the controlLoopName comes from the policy 
290      * @param requestID the requestId for this event
291      * @param status could be onset or abated
292      */
293     protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
294         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
295         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
296         event.requestID = requestID;
297         event.target = "vserver.vserver-name";
298         event.closedLoopAlarmStart = Instant.now();
299         event.AAI = new HashMap<>();
300         event.AAI.put("vserver.vserver-name", "dfw1lb01lb01");
301         event.AAI.put("vserver.is-closed-loop-disabled", "false");
302         event.closedLoopEventStatus = status;
303         kieSession.insert(event);
304     }
305     
306     /**
307      * This method will dump all the facts in the working memory.
308      * 
309      * @param kieSession the session containing the facts
310      */
311     public void dumpFacts(KieSession kieSession) {
312         logger.debug("Fact Count: {}", kieSession.getFactCount());
313         for (FactHandle handle : kieSession.getFactHandles()) {
314             logger.debug("FACT: {}", handle);
315         }
316     }
317 }