2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.policy.template.demo;
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;
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;
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;
65 public class VfcControlLoopTest implements TopicListener {
67 private static final Logger logger = LoggerFactory.getLogger(VfcControlLoopTest.class);
69 private static List<? extends TopicSink> noopTopics;
71 private static KieSession kieSession;
72 private static SupportUtil.Pair<ControlLoopPolicy, String> pair;
73 private UUID requestId;
76 /* Set environment properties */
77 SupportUtil.setAaiProps();
78 SupportUtil.setVfcProps();
79 SupportUtil.setGuardProps();
80 SupportUtil.setPuProp();
81 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
85 * Setup the simulator.
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);
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));
110 SupportUtil.buildAaiSim();
111 SupportUtil.buildVfcSim();
112 SupportUtil.buildGuardSim();
113 } catch (Exception e) {
114 fail(e.getMessage());
118 * Start the kie session
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) {
127 logger.debug("Could not create kieSession");
128 fail("Could not create kieSession");
133 * Tear down the simulator.
136 public static void tearDownSimulator() {
139 * Gracefully shut down the kie session
141 kieSession.dispose();
143 PolicyEngine.manager.stop();
144 HttpServletServer.factory.destroy();
145 PolicyController.factory.shutdown();
146 TopicEndpoint.manager.shutdown();
150 public void successTest() throws IOException {
153 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
154 * to be pulled from the queue
156 for (TopicSink sink : noopTopics) {
157 assertTrue(sink.start());
162 * Create a unique requestId
164 requestId = UUID.randomUUID();
167 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
170 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
172 kieSession.fireUntilHalt();
174 // allow object clean-up
175 kieSession.fireAllRules();
178 * The only fact in memory should be Params
180 assertEquals(1, kieSession.getFactCount());
183 * Print what's left in memory
185 dumpFacts(kieSession);
189 public void nullRequestTest() throws IOException {
192 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
193 * to be pulled from the queue
195 for (TopicSink sink : noopTopics) {
196 assertTrue(sink.start());
201 * Create a unique requestId
203 requestId = UUID.randomUUID();
206 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
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);
223 kieSession.fireUntilHalt();
225 // allow object clean-up
226 kieSession.fireAllRules();
229 * The only fact in memory should be Params
231 assertEquals(1, kieSession.getFactCount());
234 * Print what's left in memory
236 dumpFacts(kieSession);
240 * This method will start a kie session and instantiate the Policy Engine.
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
250 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
251 String policyName, String policyVersion) throws IOException {
254 * Load policies from yaml
256 pair = SupportUtil.loadYaml(yamlFile);
258 assertNotNull(pair.first);
259 assertNotNull(pair.first.getControlLoop());
260 assertNotNull(pair.first.getControlLoop().getControlLoopName());
261 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
264 * Construct a kie session
266 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
267 pair.first.getControlLoop().getControlLoopName(),
268 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
271 * Retrieve the Policy Engine
274 logger.debug("============");
275 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
276 logger.debug("============");
284 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
287 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
289 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
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);
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());
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());
334 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
337 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
338 logger.debug("Rule Fired: " + notification.getPolicyName());
340 logger.debug("The control loop timed out");
341 fail("Control Loop Timed Out");
343 } else if (obj instanceof VFCRequest) {
344 logger.debug("\n============ VFC received the request!!! ===========\n");
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).
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
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);
377 * Dumps the kie session facts.
379 * @param kieSession input session
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);