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();
165 * The only fact in memory should be Params
167 assertEquals(1, kieSession.getFactCount());
170 * Print what's left in memory
172 dumpFacts(kieSession);
176 public void namedQueryFailTest() {
179 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
180 * to be pulled from the queue
182 for (TopicSink sink : noopTopics) {
183 assertTrue(sink.start());
188 * Create a unique requestId
190 requestId = UUID.randomUUID();
193 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
196 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error");
198 kieSession.fireUntilHalt();
201 * The only fact in memory should be Params
203 assertEquals(1, kieSession.getFactCount());
206 * Print what's left in memory
208 dumpFacts(kieSession);
212 public void aaiGetFailTest() {
215 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
216 * to be pulled from the queue
218 for (TopicSink sink : noopTopics) {
219 assertTrue(sink.start());
224 * Create a unique requestId
226 requestId = UUID.randomUUID();
229 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
232 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail");
235 kieSession.fireUntilHalt();
236 } catch (Exception e) {
238 logger.warn(e.toString());
239 fail(e.getMessage());
244 * The only fact in memory should be Params
246 assertEquals(1, kieSession.getFactCount());
249 * Print what's left in memory
251 dumpFacts(kieSession);
255 * This method will start a kie session and instantiate the Policy Engine.
257 * @param droolsTemplate the DRL rules file
258 * @param yamlFile the yaml file containing the policies
259 * @param policyScope scope for policy
260 * @param policyName name of the policy
261 * @param policyVersion version of the policy
262 * @return the kieSession to be used to insert facts
263 * @throws IOException IO Exception
265 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
266 String policyName, String policyVersion) throws IOException {
269 * Load policies from yaml
271 pair = Util.loadYaml(yamlFile);
273 assertNotNull(pair.first);
274 assertNotNull(pair.first.getControlLoop());
275 assertNotNull(pair.first.getControlLoop().getControlLoopName());
276 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
279 * Construct a kie session
281 final KieSession kieSession = Util.buildContainer(droolsTemplate,
282 pair.first.getControlLoop().getControlLoopName(),
283 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
286 * Retrieve the Policy Engine
289 logger.debug("============");
290 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
291 logger.debug("============");
299 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
302 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
304 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
308 if ("POLICY-CL-MGT".equals(topic)) {
309 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
310 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
313 if (obj instanceof VirtualControlLoopNotification) {
314 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
315 String policyName = notification.getPolicyName();
316 if (policyName.endsWith("EVENT")) {
317 logger.debug("Rule Fired: " + notification.getPolicyName());
318 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
319 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
320 logger.debug("Rule Fired: " + notification.getPolicyName());
321 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
322 assertNotNull(notification.getMessage());
323 assertTrue(notification.getMessage().startsWith("Sending guard query"));
324 } else if (policyName.endsWith("GUARD.RESPONSE")) {
325 logger.debug("Rule Fired: " + notification.getPolicyName());
326 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
327 assertNotNull(notification.getMessage());
328 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
329 } else if (policyName.endsWith("GUARD_PERMITTED")) {
330 logger.debug("Rule Fired: " + notification.getPolicyName());
331 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
332 assertNotNull(notification.getMessage());
333 assertTrue(notification.getMessage().startsWith("actor=SO"));
334 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
335 logger.debug("Rule Fired: " + notification.getPolicyName());
337 logger.debug("The operation timed out");
338 fail("Operation Timed Out");
339 } else if (policyName.endsWith("SO.RESPONSE")) {
340 logger.debug("Rule Fired: " + notification.getPolicyName());
341 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
342 assertNotNull(notification.getMessage());
343 assertTrue(notification.getMessage().startsWith("actor=SO"));
344 } else if (policyName.endsWith("EVENT.MANAGER")) {
345 logger.debug("Rule Fired: " + notification.getPolicyName());
346 if ("error".equals(notification.getAai().get("vserver.vserver-name"))) {
347 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
348 } else if ("getFail".equals(notification.getAai().get("vserver.vserver-name"))) {
349 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
351 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
354 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
355 logger.debug("Rule Fired: " + notification.getPolicyName());
357 logger.debug("The control loop timed out");
358 fail("Control Loop Timed Out");
360 } else if (obj instanceof SORequest) {
361 logger.debug("\n============ SO received the request!!! ===========\n");
366 * This method is used to simulate event messages from DCAE that start the control loop (onset
367 * message) or end the control loop (abatement message).
369 * @param policy the controlLoopName comes from the policy
370 * @param requestID the requestId for this event
371 * @param status could be onset or abated
373 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
374 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
375 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
376 event.setRequestId(requestId);
377 event.setTarget("vserver.vserver-name");
378 event.setClosedLoopAlarmStart(Instant.now());
379 event.setAai(new HashMap<>());
380 event.getAai().put("vserver.vserver-name", "dfw1lb01lb01");
381 event.getAai().put("vserver.is-closed-loop-disabled", "false");
382 event.getAai().put("vserver.prov-status", "ACTIVE");
383 event.setClosedLoopEventStatus(status);
384 kieSession.insert(event);
387 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
388 String vserverName) {
389 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
390 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
391 event.setRequestId(requestId);
392 event.setTarget("vserver.vserver-name");
393 event.setClosedLoopAlarmStart(Instant.now());
394 event.setAai(new HashMap<>());
395 event.getAai().put("vserver.vserver-name", vserverName);
396 event.setClosedLoopEventStatus(status);
397 kieSession.insert(event);
401 * This method will dump all the facts in the working memory.
403 * @param kieSession the session containing the facts
405 public void dumpFacts(KieSession kieSession) {
406 logger.debug("Fact Count: {}", kieSession.getFactCount());
407 for (FactHandle handle : kieSession.getFactHandles()) {
408 logger.debug("FACT: {}", handle);