2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.template.demo;
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
28 import java.io.IOException;
29 import java.net.URLEncoder;
30 import java.time.Instant;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Properties;
34 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.controlloop.ControlLoopEventStatus;
42 import org.onap.policy.controlloop.ControlLoopNotificationType;
43 import org.onap.policy.controlloop.VirtualControlLoopEvent;
44 import org.onap.policy.controlloop.VirtualControlLoopNotification;
45 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
46 import org.onap.policy.drools.event.comm.TopicEndpoint;
47 import org.onap.policy.drools.event.comm.TopicListener;
48 import org.onap.policy.drools.event.comm.TopicSink;
49 import org.onap.policy.drools.event.comm.Topic.CommInfrastructure;
50 import org.onap.policy.drools.http.server.HttpServletServer;
51 import org.onap.policy.drools.properties.PolicyProperties;
52 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
53 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
54 import org.onap.policy.drools.system.PolicyController;
55 import org.onap.policy.drools.system.PolicyEngine;
56 import org.onap.policy.drools.utils.LoggerUtil;
57 import org.onap.policy.so.SORequest;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
61 public class VDNSControlLoopTest implements TopicListener {
63 private static final Logger logger = LoggerFactory.getLogger(VDNSControlLoopTest.class);
65 private static List<? extends TopicSink> noopTopics;
67 private static KieSession kieSession;
68 private static Util.Pair<ControlLoopPolicy, String> pair;
69 private UUID requestID;
72 /* Set environment properties */
77 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
81 public static void setUpSimulator() {
82 PolicyEngine.manager.configure(new Properties());
83 assertTrue(PolicyEngine.manager.start());
84 Properties noopSinkProperties = new Properties();
85 noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
86 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", "org.onap.policy.controlloop.VirtualControlLoopNotification");
87 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", "org.onap.policy.controlloop.util.Serialization,gsonPretty");
88 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
90 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, 1111);
96 } catch (Exception e) {
101 * Start the kie session
104 kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
105 "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml",
109 } catch (IOException e) {
111 logger.debug("Could not create kieSession");
112 fail("Could not create kieSession");
117 public static void tearDownSimulator() {
120 * Gracefully shut down the kie session
122 kieSession.dispose();
124 PolicyEngine.manager.stop();
125 HttpServletServer.factory.destroy();
126 PolicyController.factory.shutdown();
127 TopicEndpoint.manager.shutdown();
131 public void successTest() {
134 * Allows the PolicyEngine to callback to this object to
135 * notify that there is an event ready to be pulled
138 for (TopicSink sink : noopTopics) {
139 assertTrue(sink.start());
144 * Create a unique requestId
146 requestID = UUID.randomUUID();
149 * Simulate an onset event the policy engine will
150 * receive from DCAE to kick off processing through
153 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
155 kieSession.fireUntilHalt();
158 * The only fact in memory should be Params
160 assertEquals(1, kieSession.getFactCount());
163 * Print what's left in memory
165 dumpFacts(kieSession);
169 public void namedQueryFailTest() {
172 * Allows the PolicyEngine to callback to this object to
173 * notify that there is an event ready to be pulled
176 for (TopicSink sink : noopTopics) {
177 assertTrue(sink.start());
182 * Create a unique requestId
184 requestID = UUID.randomUUID();
187 * Simulate an onset event the policy engine will
188 * receive from DCAE to kick off processing through
191 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "error");
193 kieSession.fireUntilHalt();
196 * The only fact in memory should be Params
198 assertEquals(1, kieSession.getFactCount());
201 * Print what's left in memory
203 dumpFacts(kieSession);
207 public void aaiGetFailTest() {
210 * Allows the PolicyEngine to callback to this object to
211 * notify that there is an event ready to be pulled
214 for (TopicSink sink : noopTopics) {
215 assertTrue(sink.start());
220 * Create a unique requestId
222 requestID = UUID.randomUUID();
225 * Simulate an onset event the policy engine will
226 * receive from DCAE to kick off processing through
229 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail");
232 kieSession.fireUntilHalt();
234 catch (Exception e) {
236 logger.warn(e.toString());
237 fail(e.getMessage());
242 * The only fact in memory should be Params
244 assertEquals(1, kieSession.getFactCount());
247 * Print what's left in memory
249 dumpFacts(kieSession);
253 * This method will start a kie session and instantiate
256 * @param droolsTemplate
259 * the yaml file containing the policies
264 * @param policyVersion
265 * version of the policy
266 * @return the kieSession to be used to insert facts
267 * @throws IOException
269 private static KieSession startSession(String droolsTemplate,
273 String policyVersion) throws IOException {
276 * Load policies from yaml
278 pair = Util.loadYaml(yamlFile);
280 assertNotNull(pair.a);
281 assertNotNull(pair.a.getControlLoop());
282 assertNotNull(pair.a.getControlLoop().getControlLoopName());
283 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
286 * Construct a kie session
288 final KieSession kieSession = Util.buildContainer(droolsTemplate,
289 pair.a.getControlLoop().getControlLoopName(),
293 URLEncoder.encode(pair.b, "UTF-8"));
296 * Retrieve the Policy Engine
299 logger.debug("============");
300 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
301 logger.debug("============");
308 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
310 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
312 * Pull the object that was sent out to DMAAP and make
313 * sure it is a ControlLoopNoticiation of type active
316 if ("POLICY-CL-MGT".equals(topic)) {
317 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
320 if (obj instanceof VirtualControlLoopNotification) {
321 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
322 String policyName = notification.policyName;
323 if (policyName.endsWith("EVENT")) {
324 logger.debug("Rule Fired: " + notification.policyName);
325 if ("getFail".equals(notification.AAI.get("generic-vnf.vnf-id"))) {
326 assertEquals(ControlLoopNotificationType.REJECTED, notification.notification);
330 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
333 else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
334 logger.debug("Rule Fired: " + notification.policyName);
335 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
336 assertNotNull(notification.message);
337 assertTrue(notification.message.startsWith("Sending guard query"));
339 else if (policyName.endsWith("GUARD.RESPONSE")) {
340 logger.debug("Rule Fired: " + notification.policyName);
341 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
342 assertNotNull(notification.message);
343 assertTrue(notification.message.toLowerCase().endsWith("permit"));
345 else if (policyName.endsWith("GUARD_PERMITTED")) {
346 logger.debug("Rule Fired: " + notification.policyName);
347 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
348 assertNotNull(notification.message);
349 assertTrue(notification.message.startsWith("actor=SO"));
351 else if (policyName.endsWith("OPERATION.TIMEOUT")) {
352 logger.debug("Rule Fired: " + notification.policyName);
354 logger.debug("The operation timed out");
355 fail("Operation Timed Out");
357 else if (policyName.endsWith("SO.RESPONSE")) {
358 logger.debug("Rule Fired: " + notification.policyName);
359 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
360 assertNotNull(notification.message);
361 assertTrue(notification.message.startsWith("actor=SO"));
363 else if (policyName.endsWith("EVENT.MANAGER")) {
364 logger.debug("Rule Fired: " + notification.policyName);
365 if ("error".equals(notification.AAI.get("vserver.vserver-name"))) {
366 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.notification);
369 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
373 else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
374 logger.debug("Rule Fired: " + notification.policyName);
376 logger.debug("The control loop timed out");
377 fail("Control Loop Timed Out");
380 else if (obj instanceof SORequest) {
381 logger.debug("\n============ SO received the request!!! ===========\n");
386 * This method is used to simulate event messages from DCAE
387 * that start the control loop (onset message) or end the
388 * control loop (abatement message).
390 * @param policy the controlLoopName comes from the policy
391 * @param requestID the requestId for this event
392 * @param status could be onset or abated
394 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
395 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
396 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
397 event.requestID = requestID;
398 event.target = "vserver.vserver-name";
399 event.closedLoopAlarmStart = Instant.now();
400 event.AAI = new HashMap<>();
401 event.AAI.put("vserver.vserver-name", "dfw1lb01lb01");
402 event.AAI.put("vserver.is-closed-loop-disabled", "false");
403 event.closedLoopEventStatus = status;
404 kieSession.insert(event);
407 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String vserverName) {
408 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
409 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
410 event.requestID = requestID;
411 event.target = "vserver.vserver-name";
412 event.closedLoopAlarmStart = Instant.now();
413 event.AAI = new HashMap<>();
414 event.AAI.put("vserver.vserver-name", vserverName);
415 event.closedLoopEventStatus = status;
416 kieSession.insert(event);
420 * This method will dump all the facts in the working memory.
422 * @param kieSession the session containing the facts
424 public void dumpFacts(KieSession kieSession) {
425 logger.debug("Fact Count: {}", kieSession.getFactCount());
426 for (FactHandle handle : kieSession.getFactHandles()) {
427 logger.debug("FACT: {}", handle);