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