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 * Setup the simulator.
84 public static void setUpSimulator() {
85 PolicyEngine.manager.configure(new Properties());
86 assertTrue(PolicyEngine.manager.start());
87 Properties noopSinkProperties = new Properties();
88 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
89 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
90 "org.onap.policy.controlloop.VirtualControlLoopNotification");
91 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
92 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
93 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
95 EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
96 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
102 Util.buildGuardSim();
103 } catch (Exception e) {
104 fail(e.getMessage());
108 * Start the kie session
111 kieSession = startSession(
112 "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
113 + "src/main/resources/__closedLoopControlName__.drl",
114 "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml", "type=operational", "CL_vDNS", "v2.0");
115 } catch (IOException e) {
117 logger.debug("Could not create kieSession");
118 fail("Could not create kieSession");
123 * Tear down the simulator.
126 public static void tearDownSimulator() {
129 * Gracefully shut down the kie session
131 kieSession.dispose();
133 PolicyEngine.manager.stop();
134 HttpServletServer.factory.destroy();
135 PolicyController.factory.shutdown();
136 TopicEndpoint.manager.shutdown();
140 public void successTest() {
143 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
144 * to be pulled from the queue
146 for (TopicSink sink : noopTopics) {
147 assertTrue(sink.start());
152 * Create a unique requestId
154 requestId = UUID.randomUUID();
157 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
160 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
162 kieSession.fireUntilHalt();
164 // allow object clean-up
165 kieSession.fireAllRules();
168 * The only fact in memory should be Params
170 assertEquals(1, kieSession.getFactCount());
173 * Print what's left in memory
175 dumpFacts(kieSession);
179 public void namedQueryFailTest() {
182 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
183 * to be pulled from the queue
185 for (TopicSink sink : noopTopics) {
186 assertTrue(sink.start());
191 * Create a unique requestId
193 requestId = UUID.randomUUID();
196 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
199 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error");
201 kieSession.fireUntilHalt();
203 // allow object clean-up
204 kieSession.fireAllRules();
207 * The only fact in memory should be Params
209 assertEquals(1, kieSession.getFactCount());
212 * Print what's left in memory
214 dumpFacts(kieSession);
218 public void aaiGetFailTest() {
221 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
222 * to be pulled from the queue
224 for (TopicSink sink : noopTopics) {
225 assertTrue(sink.start());
230 * Create a unique requestId
232 requestId = UUID.randomUUID();
235 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
238 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail");
241 kieSession.fireUntilHalt();
243 // allow object clean-up
244 kieSession.fireAllRules();
246 } catch (Exception e) {
248 logger.warn(e.toString());
249 fail(e.getMessage());
254 * The only fact in memory should be Params
256 assertEquals(1, kieSession.getFactCount());
259 * Print what's left in memory
261 dumpFacts(kieSession);
265 * This method will start a kie session and instantiate the Policy Engine.
267 * @param droolsTemplate the DRL rules file
268 * @param yamlFile the yaml file containing the policies
269 * @param policyScope scope for policy
270 * @param policyName name of the policy
271 * @param policyVersion version of the policy
272 * @return the kieSession to be used to insert facts
273 * @throws IOException IO Exception
275 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
276 String policyName, String policyVersion) throws IOException {
279 * Load policies from yaml
281 pair = Util.loadYaml(yamlFile);
283 assertNotNull(pair.first);
284 assertNotNull(pair.first.getControlLoop());
285 assertNotNull(pair.first.getControlLoop().getControlLoopName());
286 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
289 * Construct a kie session
291 final KieSession kieSession = Util.buildContainer(droolsTemplate,
292 pair.first.getControlLoop().getControlLoopName(),
293 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
296 * Retrieve the Policy Engine
299 logger.debug("============");
300 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
301 logger.debug("============");
309 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
312 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
314 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
318 if ("POLICY-CL-MGT".equals(topic)) {
319 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
320 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
323 if (obj instanceof VirtualControlLoopNotification) {
324 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
325 String policyName = notification.getPolicyName();
326 if (policyName.endsWith("EVENT")) {
327 logger.debug("Rule Fired: " + notification.getPolicyName());
328 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
329 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
330 logger.debug("Rule Fired: " + notification.getPolicyName());
331 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
332 assertNotNull(notification.getMessage());
333 assertTrue(notification.getMessage().startsWith("Sending guard query"));
334 } else if (policyName.endsWith("GUARD.RESPONSE")) {
335 logger.debug("Rule Fired: " + notification.getPolicyName());
336 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
337 assertNotNull(notification.getMessage());
338 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
339 } else if (policyName.endsWith("GUARD_PERMITTED")) {
340 logger.debug("Rule Fired: " + notification.getPolicyName());
341 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
342 assertNotNull(notification.getMessage());
343 assertTrue(notification.getMessage().startsWith("actor=SO"));
344 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
345 logger.debug("Rule Fired: " + notification.getPolicyName());
347 logger.debug("The operation timed out");
348 fail("Operation Timed Out");
349 } else if (policyName.endsWith("SO.RESPONSE")) {
350 logger.debug("Rule Fired: " + notification.getPolicyName());
351 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
352 assertNotNull(notification.getMessage());
353 assertTrue(notification.getMessage().startsWith("actor=SO"));
354 } else if (policyName.endsWith("EVENT.MANAGER")) {
355 logger.debug("Rule Fired: " + notification.getPolicyName());
356 if ("error".equals(notification.getAai().get("vserver.vserver-name"))) {
357 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
358 } else if ("getFail".equals(notification.getAai().get("vserver.vserver-name"))) {
359 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
361 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
364 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
365 logger.debug("Rule Fired: " + notification.getPolicyName());
367 logger.debug("The control loop timed out");
368 fail("Control Loop Timed Out");
370 } else if (obj instanceof SORequest) {
371 logger.debug("\n============ SO received the request!!! ===========\n");
376 * This method is used to simulate event messages from DCAE that start the control loop (onset
377 * message) or end the control loop (abatement message).
379 * @param policy the controlLoopName comes from the policy
380 * @param requestID the requestId for this event
381 * @param status could be onset or abated
383 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
384 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
385 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
386 event.setRequestId(requestId);
387 event.setTarget("vserver.vserver-name");
388 event.setClosedLoopAlarmStart(Instant.now());
389 event.setAai(new HashMap<>());
390 event.getAai().put("vserver.vserver-name", "dfw1lb01lb01");
391 event.getAai().put("vserver.is-closed-loop-disabled", "false");
392 event.getAai().put("vserver.prov-status", "ACTIVE");
393 event.setClosedLoopEventStatus(status);
394 kieSession.insert(event);
397 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
398 String vserverName) {
399 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
400 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
401 event.setRequestId(requestId);
402 event.setTarget("vserver.vserver-name");
403 event.setClosedLoopAlarmStart(Instant.now());
404 event.setAai(new HashMap<>());
405 event.getAai().put("vserver.vserver-name", vserverName);
406 event.setClosedLoopEventStatus(status);
407 kieSession.insert(event);
411 * This method will dump all the facts in the working memory.
413 * @param kieSession the session containing the facts
415 public void dumpFacts(KieSession kieSession) {
416 logger.debug("Fact Count: {}", kieSession.getFactCount());
417 for (FactHandle handle : kieSession.getFactHandles()) {
418 logger.debug("FACT: {}", handle);