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