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.PolicyEngine;
55 import org.onap.policy.so.SORequest;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 public class VDNSControlLoopTest implements TopicListener {
61 private static final Logger logger = LoggerFactory.getLogger(VDNSControlLoopTest.class);
63 private static List<? extends TopicSink> noopTopics;
65 private static KieSession kieSession;
66 private static Util.Pair<ControlLoopPolicy, String> pair;
67 private UUID requestID;
70 /* Set environment properties */
78 public static void setUpSimulator() {
79 PolicyEngine.manager.configure(new Properties());
80 assertTrue(PolicyEngine.manager.start());
81 Properties noopSinkProperties = new Properties();
82 noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
83 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", "org.onap.policy.controlloop.VirtualControlLoopNotification");
84 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", "org.onap.policy.controlloop.util.Serialization,gsonPretty");
85 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
87 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, 1111);
93 } catch (Exception e) {
98 * Start the kie session
101 kieSession = startSession("../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
102 "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml",
106 } catch (IOException e) {
108 logger.debug("Could not create kieSession");
109 fail("Could not create kieSession");
114 public static void tearDownSimulator() {
117 * Gracefully shut down the kie session
119 kieSession.dispose();
121 HttpServletServer.factory.destroy();
122 PolicyEngine.manager.shutdown();
123 TopicEndpoint.manager.shutdown();
124 PolicyEngine.manager.stop();
128 public void successTest() {
131 * Allows the PolicyEngine to callback to this object to
132 * notify that there is an event ready to be pulled
135 for (TopicSink sink : noopTopics) {
136 assertTrue(sink.start());
141 * Create a unique requestId
143 requestID = UUID.randomUUID();
146 * Simulate an onset event the policy engine will
147 * receive from DCAE to kick off processing through
150 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET);
152 kieSession.fireUntilHalt();
155 * The only fact in memory should be Params
157 assertEquals(1, kieSession.getFactCount());
160 * Print what's left in memory
162 dumpFacts(kieSession);
166 public void namedQueryFailTest() {
169 * Allows the PolicyEngine to callback to this object to
170 * notify that there is an event ready to be pulled
173 for (TopicSink sink : noopTopics) {
174 assertTrue(sink.start());
179 * Create a unique requestId
181 requestID = UUID.randomUUID();
184 * Simulate an onset event the policy engine will
185 * receive from DCAE to kick off processing through
188 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "error");
190 kieSession.fireUntilHalt();
193 * The only fact in memory should be Params
195 assertEquals(1, kieSession.getFactCount());
198 * Print what's left in memory
200 dumpFacts(kieSession);
204 public void aaiGetFailTest() {
207 * Allows the PolicyEngine to callback to this object to
208 * notify that there is an event ready to be pulled
211 for (TopicSink sink : noopTopics) {
212 assertTrue(sink.start());
217 * Create a unique requestId
219 requestID = UUID.randomUUID();
222 * Simulate an onset event the policy engine will
223 * receive from DCAE to kick off processing through
226 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail");
229 kieSession.fireUntilHalt();
231 catch (Exception e) {
233 logger.warn(e.toString());
234 fail(e.getMessage());
239 * The only fact in memory should be Params
241 assertEquals(1, kieSession.getFactCount());
244 * Print what's left in memory
246 dumpFacts(kieSession);
250 * This method will start a kie session and instantiate
253 * @param droolsTemplate
256 * the yaml file containing the policies
261 * @param policyVersion
262 * version of the policy
263 * @return the kieSession to be used to insert facts
264 * @throws IOException
266 private static KieSession startSession(String droolsTemplate,
270 String policyVersion) throws IOException {
273 * Load policies from yaml
275 pair = Util.loadYaml(yamlFile);
277 assertNotNull(pair.a);
278 assertNotNull(pair.a.getControlLoop());
279 assertNotNull(pair.a.getControlLoop().getControlLoopName());
280 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
283 * Construct a kie session
285 final KieSession kieSession = Util.buildContainer(droolsTemplate,
286 pair.a.getControlLoop().getControlLoopName(),
290 URLEncoder.encode(pair.b, "UTF-8"));
293 * Retrieve the Policy Engine
296 logger.debug("============");
297 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
298 logger.debug("============");
305 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
307 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
309 * Pull the object that was sent out to DMAAP and make
310 * sure it is a ControlLoopNoticiation of type active
313 if ("POLICY-CL-MGT".equals(topic)) {
314 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, org.onap.policy.controlloop.VirtualControlLoopNotification.class);
317 if (obj instanceof VirtualControlLoopNotification) {
318 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
319 String policyName = notification.policyName;
320 if (policyName.endsWith("EVENT")) {
321 logger.debug("Rule Fired: " + notification.policyName);
322 if ("getFail".equals(notification.AAI.get("generic-vnf.vnf-id"))) {
323 assertEquals(ControlLoopNotificationType.REJECTED, notification.notification);
327 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.notification));
330 else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
331 logger.debug("Rule Fired: " + notification.policyName);
332 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
333 assertNotNull(notification.message);
334 assertTrue(notification.message.startsWith("Sending guard query"));
336 else if (policyName.endsWith("GUARD.RESPONSE")) {
337 logger.debug("Rule Fired: " + notification.policyName);
338 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
339 assertNotNull(notification.message);
340 assertTrue(notification.message.toLowerCase().endsWith("permit"));
342 else if (policyName.endsWith("GUARD_PERMITTED")) {
343 logger.debug("Rule Fired: " + notification.policyName);
344 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.notification));
345 assertNotNull(notification.message);
346 assertTrue(notification.message.startsWith("actor=SO"));
348 else if (policyName.endsWith("OPERATION.TIMEOUT")) {
349 logger.debug("Rule Fired: " + notification.policyName);
351 logger.debug("The operation timed out");
352 fail("Operation Timed Out");
354 else if (policyName.endsWith("SO.RESPONSE")) {
355 logger.debug("Rule Fired: " + notification.policyName);
356 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.notification));
357 assertNotNull(notification.message);
358 assertTrue(notification.message.startsWith("actor=SO"));
360 else if (policyName.endsWith("EVENT.MANAGER")) {
361 logger.debug("Rule Fired: " + notification.policyName);
362 if ("error".equals(notification.AAI.get("vserver.vserver-name"))) {
363 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.notification);
366 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.notification));
370 else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
371 logger.debug("Rule Fired: " + notification.policyName);
373 logger.debug("The control loop timed out");
374 fail("Control Loop Timed Out");
377 else if (obj instanceof SORequest) {
378 logger.debug("\n============ SO received the request!!! ===========\n");
383 * This method is used to simulate event messages from DCAE
384 * that start the control loop (onset message) or end the
385 * control loop (abatement message).
387 * @param policy the controlLoopName comes from the policy
388 * @param requestID the requestId for this event
389 * @param status could be onset or abated
391 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
392 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
393 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
394 event.requestID = requestID;
395 event.target = "vserver.vserver-name";
396 event.closedLoopAlarmStart = Instant.now();
397 event.AAI = new HashMap<>();
398 event.AAI.put("vserver.vserver-name", "dfw1lb01lb01");
399 event.AAI.put("vserver.is-closed-loop-disabled", "false");
400 event.closedLoopEventStatus = status;
401 kieSession.insert(event);
404 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String vserverName) {
405 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
406 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
407 event.requestID = requestID;
408 event.target = "vserver.vserver-name";
409 event.closedLoopAlarmStart = Instant.now();
410 event.AAI = new HashMap<>();
411 event.AAI.put("vserver.vserver-name", vserverName);
412 event.closedLoopEventStatus = status;
413 kieSession.insert(event);
417 * This method will dump all the facts in the working memory.
419 * @param kieSession the session containing the facts
421 public void dumpFacts(KieSession kieSession) {
422 logger.debug("Fact Count: {}", kieSession.getFactCount());
423 for (FactHandle handle : kieSession.getFactHandles()) {
424 logger.debug("FACT: {}", handle);