2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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.common.endpoints.event.comm.Topic.CommInfrastructure;
42 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
43 import org.onap.policy.common.endpoints.event.comm.TopicListener;
44 import org.onap.policy.common.endpoints.event.comm.TopicSink;
45 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
46 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
47 import org.onap.policy.controlloop.ControlLoopEventStatus;
48 import org.onap.policy.controlloop.ControlLoopNotificationType;
49 import org.onap.policy.controlloop.VirtualControlLoopEvent;
50 import org.onap.policy.controlloop.VirtualControlLoopNotification;
51 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
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.logging.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(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
86 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
87 "org.onap.policy.controlloop.VirtualControlLoopNotification");
88 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
89 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
90 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
92 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
93 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
100 } catch (Exception e) {
101 fail(e.getMessage());
105 * Start the kie session
108 kieSession = startSession(
109 "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl",
110 "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml", "type=operational", "CL_vDNS", "v2.0");
111 } catch (IOException e) {
113 logger.debug("Could not create kieSession");
114 fail("Could not create kieSession");
119 public static void tearDownSimulator() {
122 * Gracefully shut down the kie session
124 kieSession.dispose();
126 PolicyEngine.manager.stop();
127 HttpServletServer.factory.destroy();
128 PolicyController.factory.shutdown();
129 TopicEndpoint.manager.shutdown();
133 public void successTest() {
136 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
137 * to be pulled from the queue
139 for (TopicSink sink : noopTopics) {
140 assertTrue(sink.start());
145 * Create a unique requestId
147 requestID = UUID.randomUUID();
150 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
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 notify that there is an event ready
173 * to be pulled from the queue
175 for (TopicSink sink : noopTopics) {
176 assertTrue(sink.start());
181 * Create a unique requestId
183 requestID = UUID.randomUUID();
186 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
189 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "error");
191 kieSession.fireUntilHalt();
194 * The only fact in memory should be Params
196 assertEquals(1, kieSession.getFactCount());
199 * Print what's left in memory
201 dumpFacts(kieSession);
205 public void aaiGetFailTest() {
208 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
209 * to be pulled from the queue
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 receive from DCAE to kick off processing
225 sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail");
228 kieSession.fireUntilHalt();
229 } catch (Exception e) {
231 logger.warn(e.toString());
232 fail(e.getMessage());
237 * The only fact in memory should be Params
239 assertEquals(1, kieSession.getFactCount());
242 * Print what's left in memory
244 dumpFacts(kieSession);
248 * This method will start a kie session and instantiate the Policy Engine.
250 * @param droolsTemplate the DRL rules file
251 * @param yamlFile the yaml file containing the policies
252 * @param policyScope scope for policy
253 * @param policyName name of the policy
254 * @param policyVersion version of the policy
255 * @return the kieSession to be used to insert facts
256 * @throws IOException
258 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
259 String policyName, String policyVersion) throws IOException {
262 * Load policies from yaml
264 pair = Util.loadYaml(yamlFile);
266 assertNotNull(pair.a);
267 assertNotNull(pair.a.getControlLoop());
268 assertNotNull(pair.a.getControlLoop().getControlLoopName());
269 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
272 * Construct a kie session
274 final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(),
275 policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8"));
278 * Retrieve the Policy Engine
281 logger.debug("============");
282 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
283 logger.debug("============");
291 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
294 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
296 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
300 if ("POLICY-CL-MGT".equals(topic)) {
301 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
302 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
305 if (obj instanceof VirtualControlLoopNotification) {
306 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
307 String policyName = notification.getPolicyName();
308 if (policyName.endsWith("EVENT")) {
309 logger.debug("Rule Fired: " + notification.getPolicyName());
310 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
311 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
312 logger.debug("Rule Fired: " + notification.getPolicyName());
313 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
314 assertNotNull(notification.getMessage());
315 assertTrue(notification.getMessage().startsWith("Sending guard query"));
316 } else if (policyName.endsWith("GUARD.RESPONSE")) {
317 logger.debug("Rule Fired: " + notification.getPolicyName());
318 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
319 assertNotNull(notification.getMessage());
320 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
321 } else if (policyName.endsWith("GUARD_PERMITTED")) {
322 logger.debug("Rule Fired: " + notification.getPolicyName());
323 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
324 assertNotNull(notification.getMessage());
325 assertTrue(notification.getMessage().startsWith("actor=SO"));
326 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
327 logger.debug("Rule Fired: " + notification.getPolicyName());
329 logger.debug("The operation timed out");
330 fail("Operation Timed Out");
331 } else if (policyName.endsWith("SO.RESPONSE")) {
332 logger.debug("Rule Fired: " + notification.getPolicyName());
333 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
334 assertNotNull(notification.getMessage());
335 assertTrue(notification.getMessage().startsWith("actor=SO"));
336 } else if (policyName.endsWith("EVENT.MANAGER")) {
337 logger.debug("Rule Fired: " + notification.getPolicyName());
338 if ("error".equals(notification.getAai().get("vserver.vserver-name"))) {
339 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
340 } else if ("getFail".equals(notification.getAai().get("vserver.vserver-name"))) {
341 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
343 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
346 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
347 logger.debug("Rule Fired: " + notification.getPolicyName());
349 logger.debug("The control loop timed out");
350 fail("Control Loop Timed Out");
352 } else if (obj instanceof SORequest) {
353 logger.debug("\n============ SO received the request!!! ===========\n");
358 * This method is used to simulate event messages from DCAE that start the control loop (onset
359 * message) or end the control loop (abatement message).
361 * @param policy the controlLoopName comes from the policy
362 * @param requestID the requestId for this event
363 * @param status could be onset or abated
365 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) {
366 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
367 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
368 event.setRequestId(requestID);
369 event.setTarget("vserver.vserver-name");
370 event.setClosedLoopAlarmStart(Instant.now());
371 event.setAai(new HashMap<>());
372 event.getAai().put("vserver.vserver-name", "dfw1lb01lb01");
373 event.getAai().put("vserver.is-closed-loop-disabled", "false");
374 event.setClosedLoopEventStatus(status);
375 kieSession.insert(event);
378 protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status,
379 String vserverName) {
380 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
381 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
382 event.setRequestId(requestID);
383 event.setTarget("vserver.vserver-name");
384 event.setClosedLoopAlarmStart(Instant.now());
385 event.setAai(new HashMap<>());
386 event.getAai().put("vserver.vserver-name", vserverName);
387 event.setClosedLoopEventStatus(status);
388 kieSession.insert(event);
392 * This method will dump all the facts in the working memory.
394 * @param kieSession the session containing the facts
396 public void dumpFacts(KieSession kieSession) {
397 logger.debug("Fact Count: {}", kieSession.getFactCount());
398 for (FactHandle handle : kieSession.getFactHandles()) {
399 logger.debug("FACT: {}", handle);