2 * ============LICENSE_START=======================================================
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
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 .modelClassLoaderHash(1111));
108 SupportUtil.buildAaiSim();
109 SupportUtil.buildVfcSim();
110 SupportUtil.buildGuardSim();
111 } catch (Exception e) {
112 fail(e.getMessage());
116 * Start the kie session
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) {
125 logger.debug("Could not create kieSession");
126 fail("Could not create kieSession");
131 * Tear down the simulator.
134 public static void tearDownSimulator() {
137 * Gracefully shut down the kie session
139 kieSession.dispose();
141 PolicyEngine.manager.stop();
142 HttpServletServer.factory.destroy();
143 PolicyController.factory.shutdown();
144 TopicEndpoint.manager.shutdown();
148 public void successTest() throws IOException {
151 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
152 * to be pulled from the queue
154 for (TopicSink sink : noopTopics) {
155 assertTrue(sink.start());
160 * Create a unique requestId
162 requestId = UUID.randomUUID();
165 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
168 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
170 kieSession.fireUntilHalt();
172 // allow object clean-up
173 kieSession.fireAllRules();
176 * The only fact in memory should be Params
178 assertEquals(1, kieSession.getFactCount());
181 * Print what's left in memory
183 dumpFacts(kieSession);
187 public void nullRequestTest() throws IOException {
190 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
191 * to be pulled from the queue
193 for (TopicSink sink : noopTopics) {
194 assertTrue(sink.start());
199 * Create a unique requestId
201 requestId = UUID.randomUUID();
204 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
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);
221 kieSession.fireUntilHalt();
223 // allow object clean-up
224 kieSession.fireAllRules();
227 * The only fact in memory should be Params
229 assertEquals(1, kieSession.getFactCount());
232 * Print what's left in memory
234 dumpFacts(kieSession);
238 * This method will start a kie session and instantiate the Policy Engine.
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
248 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
249 String policyName, String policyVersion) throws IOException {
252 * Load policies from yaml
254 pair = SupportUtil.loadYaml(yamlFile);
256 assertNotNull(pair.first);
257 assertNotNull(pair.first.getControlLoop());
258 assertNotNull(pair.first.getControlLoop().getControlLoopName());
259 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
262 * Construct a kie session
264 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
265 pair.first.getControlLoop().getControlLoopName(),
266 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
269 * Retrieve the Policy Engine
272 logger.debug("============");
273 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
274 logger.debug("============");
282 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
285 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
287 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
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);
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());
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());
332 assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification());
335 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
336 logger.debug("Rule Fired: " + notification.getPolicyName());
338 logger.debug("The control loop timed out");
339 fail("Control Loop Timed Out");
341 } else if (obj instanceof VfcRequest) {
342 logger.debug("\n============ VFC received the request!!! ===========\n");
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).
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
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);
375 * Dumps the kie session facts.
377 * @param kieSession input session
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);