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