aa4c108c582f41c25e50ccbf8558f06d4eced164
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
4  * ================================================================================
5  * Copyright (C) 2017-2018 Intel Corp. All rights reserved.
6  * Modifications Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.template.demo;
23
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
28
29 import java.io.IOException;
30 import java.net.URLEncoder;
31 import java.time.Instant;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Properties;
35 import java.util.UUID;
36
37 import org.junit.AfterClass;
38 import org.junit.BeforeClass;
39 import org.junit.Test;
40 import org.kie.api.runtime.KieSession;
41 import org.kie.api.runtime.rule.FactHandle;
42 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
43 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
44 import org.onap.policy.common.endpoints.event.comm.TopicListener;
45 import org.onap.policy.common.endpoints.event.comm.TopicSink;
46 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
47 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
48 import org.onap.policy.controlloop.ControlLoopEventStatus;
49 import org.onap.policy.controlloop.ControlLoopNotificationType;
50 import org.onap.policy.controlloop.ControlLoopTargetType;
51 import org.onap.policy.controlloop.VirtualControlLoopEvent;
52 import org.onap.policy.controlloop.VirtualControlLoopNotification;
53 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
54 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
55 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
56 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
57 import org.onap.policy.drools.system.PolicyController;
58 import org.onap.policy.drools.system.PolicyEngine;
59 import org.onap.policy.drools.utils.logging.LoggerUtil;
60 import org.onap.policy.vfc.VFCRequest;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64
65 public class VfcControlLoopTest implements TopicListener {
66
67     private static final Logger logger = LoggerFactory.getLogger(VfcControlLoopTest.class);
68
69     private static List<? extends TopicSink> noopTopics;
70
71     private static KieSession kieSession;
72     private static SupportUtil.Pair<ControlLoopPolicy, String> pair;
73     private UUID requestId;
74
75     static {
76         /* Set environment properties */
77         SupportUtil.setAaiProps();
78         SupportUtil.setVfcProps();
79         SupportUtil.setGuardProps();
80         SupportUtil.setPuProp();
81         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
82     }
83
84     /**
85      * Setup the simulator.
86      */
87     @BeforeClass
88     public static void setUpSimulator() {
89         PolicyEngine.manager.configure(new Properties());
90         assertTrue(PolicyEngine.manager.start());
91         Properties noopSinkProperties = new Properties();
92         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
93         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
94                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
95         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
96                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
97         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
98
99         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
100                 .groupId("junit.groupId")
101                 .artifactId("junit.artifactId")
102                 .topic("POLICY-CL-MGT")
103                 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
104                 .protocolFilter(new JsonProtocolFilter())
105                 .customGsonCoder(null)
106                 .customJacksonCoder(null)
107                 .modelClassLoaderHash(1111));
108
109         try {
110             SupportUtil.buildAaiSim();
111             SupportUtil.buildVfcSim();
112             SupportUtil.buildGuardSim();
113         } catch (Exception e) {
114             fail(e.getMessage());
115         }
116         /*
117          * 
118          * Start the kie session
119          */
120         try {
121             kieSession = startSession(
122                     "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
123                     + "src/main/resources/__closedLoopControlName__.drl",
124                     "src/test/resources/yaml/policy_ControlLoop_VFC.yaml", "type=operational", "CL_VoLTE", "v2.0");
125         } catch (IOException e) {
126             e.printStackTrace();
127             logger.debug("Could not create kieSession");
128             fail("Could not create kieSession");
129         }
130     }
131
132     /**
133      * Tear down the simulator.
134      */
135     @AfterClass
136     public static void tearDownSimulator() {
137
138         /*
139          * Gracefully shut down the kie session
140          */
141         kieSession.dispose();
142
143         PolicyEngine.manager.stop();
144         HttpServletServer.factory.destroy();
145         PolicyController.factory.shutdown();
146         TopicEndpoint.manager.shutdown();
147     }
148
149     @Test
150     public void successTest() throws IOException {
151
152         /*
153          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
154          * to be pulled from the queue
155          */
156         for (TopicSink sink : noopTopics) {
157             assertTrue(sink.start());
158             sink.register(this);
159         }
160
161         /*
162          * Create a unique requestId
163          */
164         requestId = UUID.randomUUID();
165
166         /*
167          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
168          * through the rules
169          */
170         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
171
172         kieSession.fireUntilHalt();
173         
174         // allow object clean-up
175         kieSession.fireAllRules();
176
177         /*
178          * The only fact in memory should be Params
179          */
180         assertEquals(1, kieSession.getFactCount());
181
182         /*
183          * Print what's left in memory
184          */
185         dumpFacts(kieSession);
186     }
187
188     @Test
189     public void nullRequestTest() throws IOException {
190
191         /*
192          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
193          * to be pulled from the queue
194          */
195         for (TopicSink sink : noopTopics) {
196             assertTrue(sink.start());
197             sink.register(this);
198         }
199
200         /*
201          * Create a unique requestId
202          */
203         requestId = UUID.randomUUID();
204
205         /*
206          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
207          * through the rules
208          */
209
210         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
211         event.setClosedLoopControlName(pair.first.getControlLoop().getControlLoopName());
212         event.setRequestId(UUID.randomUUID());
213         event.setClosedLoopEventClient("tca.instance00009");
214         event.setTargetType(ControlLoopTargetType.VM);
215         event.setTarget("vserver.vserver-name");
216         event.setFrom("DCAE");
217         event.setClosedLoopAlarmStart(Instant.now());
218         event.setAai(new HashMap<String, String>());
219         event.getAai().put("vserver.vserver-name", "nullRequest");
220         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
221         kieSession.insert(event);
222
223         kieSession.fireUntilHalt();
224         
225         // allow object clean-up
226         kieSession.fireAllRules();
227
228         /*
229          * The only fact in memory should be Params
230          */
231         assertEquals(1, kieSession.getFactCount());
232
233         /*
234          * Print what's left in memory
235          */
236         dumpFacts(kieSession);
237     }
238
239     /**
240      * This method will start a kie session and instantiate the Policy Engine.
241      *
242      * @param droolsTemplate the DRL rules file
243      * @param yamlFile the yaml file containing the policies
244      * @param policyScope scope for policy
245      * @param policyName name of the policy
246      * @param policyVersion version of the policy
247      * @return the kieSession to be used to insert facts
248      * @throws IOException IO Exception
249      */
250     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
251             String policyName, String policyVersion) throws IOException {
252
253         /*
254          * Load policies from yaml
255          */
256         pair = SupportUtil.loadYaml(yamlFile);
257         assertNotNull(pair);
258         assertNotNull(pair.first);
259         assertNotNull(pair.first.getControlLoop());
260         assertNotNull(pair.first.getControlLoop().getControlLoopName());
261         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
262
263         /*
264          * Construct a kie session
265          */
266         final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate, 
267                 pair.first.getControlLoop().getControlLoopName(),
268                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
269
270         /*
271          * Retrieve the Policy Engine
272          */
273
274         logger.debug("============");
275         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
276         logger.debug("============");
277
278         return kieSession;
279     }
280
281     /*
282      * (non-Javadoc)
283      * 
284      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
285      */
286     @Override
287     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
288         /*
289          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
290          * of type active
291          */
292         Object obj = null;
293         if ("POLICY-CL-MGT".equals(topic)) {
294             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
295                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
296         }
297         assertNotNull(obj);
298         if (obj instanceof VirtualControlLoopNotification) {
299             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
300             String policyName = notification.getPolicyName();
301             if (policyName.endsWith("EVENT")) {
302                 logger.debug("Rule Fired: " + notification.getPolicyName());
303                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
304             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
305                 logger.debug("Rule Fired: " + notification.getPolicyName());
306                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
307                 assertNotNull(notification.getMessage());
308                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
309             } else if (policyName.endsWith("GUARD.RESPONSE")) {
310                 logger.debug("Rule Fired: " + notification.getPolicyName());
311                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
312                 assertNotNull(notification.getMessage());
313                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
314             } else if (policyName.endsWith("GUARD_PERMITTED")) {
315                 logger.debug("Rule Fired: " + notification.getPolicyName());
316                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
317                 assertNotNull(notification.getMessage());
318                 assertTrue(notification.getMessage().startsWith("actor=VFC"));
319             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
320                 logger.debug("Rule Fired: " + notification.getPolicyName());
321                 kieSession.halt();
322                 logger.debug("The operation timed out");
323                 fail("Operation Timed Out");
324             } else if (policyName.endsWith("VFC.RESPONSE")) {
325                 logger.debug("Rule Fired: " + notification.getPolicyName());
326                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
327                 assertNotNull(notification.getMessage());
328                 assertTrue(notification.getMessage().startsWith("actor=VFC"));
329             } else if (policyName.endsWith("EVENT.MANAGER")) {
330                 logger.debug("Rule Fired: " + notification.getPolicyName());
331                 if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) {
332                     assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
333                 } else {
334                     assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
335                 }
336                 kieSession.halt();
337             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
338                 logger.debug("Rule Fired: " + notification.getPolicyName());
339                 kieSession.halt();
340                 logger.debug("The control loop timed out");
341                 fail("Control Loop Timed Out");
342             }
343         } else if (obj instanceof VFCRequest) {
344             logger.debug("\n============ VFC received the request!!! ===========\n");
345         }
346     }
347
348     /**
349      * This method is used to simulate event messages from DCAE that start the control loop (onset
350      * message) or end the control loop (abatement message).
351      * 
352      * @param policy the controlLoopName comes from the policy
353      * @param requestId the requestId for this event
354      * @param status could be onset or abated
355      */
356     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
357         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
358         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
359         event.setRequestId(UUID.randomUUID());
360         event.setClosedLoopEventClient("tca.instance00009");
361         event.setTargetType(ControlLoopTargetType.VM);
362         event.setTarget("vserver.vserver-name");
363         event.setFrom("DCAE");
364         event.setClosedLoopAlarmStart(Instant.now());
365         event.setAai(new HashMap<String, String>());
366         event.getAai().put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
367         event.getAai().put("vserver.vserver-id", "vserver-id-16102016-aai3255-data-11-1");
368         event.getAai().put("generic-vnf.vnf-id", "vnf-id-16102016-aai3255-data-11-1");
369         event.getAai().put("service-instance.service-instance-id", "service-instance-id-16102016-aai3255-data-11-1");
370         event.getAai().put("vserver.is-closed-loop-disabled", "false");
371         event.getAai().put("vserver.prov-status", "ACTIVE");
372         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
373         kieSession.insert(event);
374     }
375
376     /**
377      * Dumps the kie session facts.
378      * 
379      * @param kieSession input session
380      */
381     public static void dumpFacts(KieSession kieSession) {
382         logger.debug("Fact Count: " + kieSession.getFactCount());
383         for (FactHandle handle : kieSession.getFactHandles()) {
384             logger.debug("FACT: " + handle);
385         }
386     }
387
388 }
389