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.EventProtocolParams;
54 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
55 import org.onap.policy.drools.system.PolicyController;
56 import org.onap.policy.drools.system.PolicyEngine;
57 import org.onap.policy.drools.utils.logging.LoggerUtil;
58 import org.onap.policy.so.SORequest;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 public class VdnsControlLoopTest implements TopicListener {
64 private static final Logger logger = LoggerFactory.getLogger(VdnsControlLoopTest.class);
66 private static List<? extends TopicSink> noopTopics;
68 private static KieSession kieSession;
69 private static Util.Pair<ControlLoopPolicy, String> pair;
70 private UUID requestId;
73 /* Set environment properties */
78 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
82 * Setup the simulator.
85 public static void setUpSimulator() {
86 PolicyEngine.manager.configure(new Properties());
87 assertTrue(PolicyEngine.manager.start());
88 Properties noopSinkProperties = new Properties();
89 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT");
90 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
91 "org.onap.policy.controlloop.VirtualControlLoopNotification");
92 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
93 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
94 noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
96 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
97 .groupId("junit.groupId")
98 .artifactId("junit.artifactId")
99 .topic("POLICY-CL-MGT")
100 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
101 .protocolFilter(new JsonProtocolFilter())
102 .customGsonCoder(null)
103 .customJacksonCoder(null)
104 .modelClassLoaderHash(1111));
109 Util.buildGuardSim();
110 } catch (Exception e) {
111 fail(e.getMessage());
115 * Start the kie session
118 kieSession = startSession(
119 "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
120 + "src/main/resources/__closedLoopControlName__.drl",
121 "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml", "type=operational", "CL_vDNS", "v2.0");
122 } catch (IOException e) {
124 logger.debug("Could not create kieSession");
125 fail("Could not create kieSession");
130 * Tear down the simulator.
133 public static void tearDownSimulator() {
136 * Gracefully shut down the kie session
138 kieSession.dispose();
140 PolicyEngine.manager.stop();
141 HttpServletServer.factory.destroy();
142 PolicyController.factory.shutdown();
143 TopicEndpoint.manager.shutdown();
147 public void successTest() {
150 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
151 * to be pulled from the queue
153 for (TopicSink sink : noopTopics) {
154 assertTrue(sink.start());
159 * Create a unique requestId
161 requestId = UUID.randomUUID();
164 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
167 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
169 kieSession.fireUntilHalt();
171 // allow object clean-up
172 kieSession.fireAllRules();
175 * The only fact in memory should be Params
177 assertEquals(1, kieSession.getFactCount());
180 * Print what's left in memory
182 dumpFacts(kieSession);
186 public void namedQueryFailTest() {
189 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
190 * to be pulled from the queue
192 for (TopicSink sink : noopTopics) {
193 assertTrue(sink.start());
198 * Create a unique requestId
200 requestId = UUID.randomUUID();
203 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
206 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error");
208 kieSession.fireUntilHalt();
210 // allow object clean-up
211 kieSession.fireAllRules();
214 * The only fact in memory should be Params
216 assertEquals(1, kieSession.getFactCount());
219 * Print what's left in memory
221 dumpFacts(kieSession);
225 public void aaiGetFailTest() {
228 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
229 * to be pulled from the queue
231 for (TopicSink sink : noopTopics) {
232 assertTrue(sink.start());
237 * Create a unique requestId
239 requestId = UUID.randomUUID();
242 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
245 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail");
248 kieSession.fireUntilHalt();
250 // allow object clean-up
251 kieSession.fireAllRules();
253 } catch (Exception e) {
255 logger.warn(e.toString());
256 fail(e.getMessage());
261 * The only fact in memory should be Params
263 assertEquals(1, kieSession.getFactCount());
266 * Print what's left in memory
268 dumpFacts(kieSession);
272 * This method will start a kie session and instantiate the Policy Engine.
274 * @param droolsTemplate the DRL rules file
275 * @param yamlFile the yaml file containing the policies
276 * @param policyScope scope for policy
277 * @param policyName name of the policy
278 * @param policyVersion version of the policy
279 * @return the kieSession to be used to insert facts
280 * @throws IOException IO Exception
282 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
283 String policyName, String policyVersion) throws IOException {
286 * Load policies from yaml
288 pair = Util.loadYaml(yamlFile);
290 assertNotNull(pair.first);
291 assertNotNull(pair.first.getControlLoop());
292 assertNotNull(pair.first.getControlLoop().getControlLoopName());
293 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
296 * Construct a kie session
298 final KieSession kieSession = Util.buildContainer(droolsTemplate,
299 pair.first.getControlLoop().getControlLoopName(),
300 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
303 * Retrieve the Policy Engine
306 logger.debug("============");
307 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
308 logger.debug("============");
316 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
319 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
321 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
325 if ("POLICY-CL-MGT".equals(topic)) {
326 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
327 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
330 if (obj instanceof VirtualControlLoopNotification) {
331 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
332 String policyName = notification.getPolicyName();
333 if (policyName.endsWith("EVENT")) {
334 logger.debug("Rule Fired: " + notification.getPolicyName());
335 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
336 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
337 logger.debug("Rule Fired: " + notification.getPolicyName());
338 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
339 assertNotNull(notification.getMessage());
340 assertTrue(notification.getMessage().startsWith("Sending guard query"));
341 } else if (policyName.endsWith("GUARD.RESPONSE")) {
342 logger.debug("Rule Fired: " + notification.getPolicyName());
343 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
344 assertNotNull(notification.getMessage());
345 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
346 } else if (policyName.endsWith("GUARD_PERMITTED")) {
347 logger.debug("Rule Fired: " + notification.getPolicyName());
348 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
349 assertNotNull(notification.getMessage());
350 assertTrue(notification.getMessage().startsWith("actor=SO"));
351 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
352 logger.debug("Rule Fired: " + notification.getPolicyName());
354 logger.debug("The operation timed out");
355 fail("Operation Timed Out");
356 } else if (policyName.endsWith("SO.RESPONSE")) {
357 logger.debug("Rule Fired: " + notification.getPolicyName());
358 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
359 assertNotNull(notification.getMessage());
360 assertTrue(notification.getMessage().startsWith("actor=SO"));
361 } else if (policyName.endsWith("EVENT.MANAGER")) {
362 logger.debug("Rule Fired: " + notification.getPolicyName());
363 if ("error".equals(notification.getAai().get("vserver.vserver-name"))) {
364 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
365 } else if ("getFail".equals(notification.getAai().get("vserver.vserver-name"))) {
366 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
368 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
371 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
372 logger.debug("Rule Fired: " + notification.getPolicyName());
374 logger.debug("The control loop timed out");
375 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 that start the control loop (onset
384 * message) or end the control loop (abatement message).
386 * @param policy the controlLoopName comes from the policy
387 * @param requestId the requestId for this event
388 * @param status could be onset or abated
390 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
391 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
392 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
393 event.setRequestId(requestId);
394 event.setTarget("vserver.vserver-name");
395 event.setClosedLoopAlarmStart(Instant.now());
396 event.setAai(new HashMap<>());
397 event.getAai().put("vserver.vserver-name", "dfw1lb01lb01");
398 event.getAai().put("vserver.is-closed-loop-disabled", "false");
399 event.getAai().put("vserver.prov-status", "ACTIVE");
400 event.setClosedLoopEventStatus(status);
401 kieSession.insert(event);
404 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
405 String vserverName) {
406 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
407 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
408 event.setRequestId(requestId);
409 event.setTarget("vserver.vserver-name");
410 event.setClosedLoopAlarmStart(Instant.now());
411 event.setAai(new HashMap<>());
412 event.getAai().put("vserver.vserver-name", vserverName);
413 event.setClosedLoopEventStatus(status);
414 kieSession.insert(event);
418 * This method will dump all the facts in the working memory.
420 * @param kieSession the session containing the facts
422 public void dumpFacts(KieSession kieSession) {
423 logger.debug("Fact Count: {}", kieSession.getFactCount());
424 for (FactHandle handle : kieSession.getFactHandles()) {
425 logger.debug("FACT: {}", handle);