2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 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 SupportUtil.Pair<ControlLoopPolicy, String> pair;
70 private UUID requestId;
73 /* Set environment properties */
74 SupportUtil.setAaiProps();
75 SupportUtil.setSoProps();
76 SupportUtil.setGuardProps();
77 SupportUtil.setPuProp();
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 .modelClassLoaderHash(1111));
105 SupportUtil.buildAaiSim();
106 SupportUtil.buildSoSim();
107 SupportUtil.buildGuardSim();
108 } catch (Exception e) {
109 fail(e.getMessage());
113 * Start the kie session
116 kieSession = startSession(
117 "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
118 + "src/main/resources/__closedLoopControlName__.drl",
119 "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml", "type=operational", "CL_vDNS", "v2.0");
120 } catch (IOException e) {
122 logger.debug("Could not create kieSession");
123 fail("Could not create kieSession");
128 * Tear down the simulator.
131 public static void tearDownSimulator() {
134 * Gracefully shut down the kie session
136 kieSession.dispose();
138 PolicyEngine.manager.stop();
139 HttpServletServer.factory.destroy();
140 PolicyController.factory.shutdown();
141 TopicEndpoint.manager.shutdown();
145 public void successTest() {
148 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
149 * to be pulled from the queue
151 for (TopicSink sink : noopTopics) {
152 assertTrue(sink.start());
157 * Create a unique requestId
159 requestId = UUID.randomUUID();
162 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
165 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
167 kieSession.fireUntilHalt();
169 // allow object clean-up
170 kieSession.fireAllRules();
173 * The only fact in memory should be Params
175 assertEquals(1, kieSession.getFactCount());
178 * Print what's left in memory
180 dumpFacts(kieSession);
184 public void namedQueryFailTest() {
187 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
188 * to be pulled from the queue
190 for (TopicSink sink : noopTopics) {
191 assertTrue(sink.start());
196 * Create a unique requestId
198 requestId = UUID.randomUUID();
201 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
204 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error");
206 kieSession.fireUntilHalt();
208 // allow object clean-up
209 kieSession.fireAllRules();
212 * The only fact in memory should be Params
214 assertEquals(1, kieSession.getFactCount());
217 * Print what's left in memory
219 dumpFacts(kieSession);
223 public void aaiGetFailTest() {
226 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
227 * to be pulled from the queue
229 for (TopicSink sink : noopTopics) {
230 assertTrue(sink.start());
235 * Create a unique requestId
237 requestId = UUID.randomUUID();
240 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
243 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail");
246 kieSession.fireUntilHalt();
248 // allow object clean-up
249 kieSession.fireAllRules();
251 } catch (Exception e) {
253 logger.warn(e.toString());
254 fail(e.getMessage());
259 * The only fact in memory should be Params
261 assertEquals(1, kieSession.getFactCount());
264 * Print what's left in memory
266 dumpFacts(kieSession);
270 * This method will start a kie session and instantiate the Policy Engine.
272 * @param droolsTemplate the DRL rules file
273 * @param yamlFile the yaml file containing the policies
274 * @param policyScope scope for policy
275 * @param policyName name of the policy
276 * @param policyVersion version of the policy
277 * @return the kieSession to be used to insert facts
278 * @throws IOException IO Exception
280 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
281 String policyName, String policyVersion) throws IOException {
284 * Load policies from yaml
286 pair = SupportUtil.loadYaml(yamlFile);
288 assertNotNull(pair.first);
289 assertNotNull(pair.first.getControlLoop());
290 assertNotNull(pair.first.getControlLoop().getControlLoopName());
291 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
294 * Construct a kie session
296 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
297 pair.first.getControlLoop().getControlLoopName(),
298 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
301 * Retrieve the Policy Engine
304 logger.debug("============");
305 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
306 logger.debug("============");
314 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
317 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
319 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
323 if ("POLICY-CL-MGT".equals(topic)) {
324 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
325 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
328 if (obj instanceof VirtualControlLoopNotification) {
329 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
330 String policyName = notification.getPolicyName();
331 if (policyName.endsWith("EVENT")) {
332 logger.debug("Rule Fired: " + notification.getPolicyName());
333 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
334 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
335 logger.debug("Rule Fired: " + notification.getPolicyName());
336 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
337 assertNotNull(notification.getMessage());
338 assertTrue(notification.getMessage().startsWith("Sending guard query"));
339 } else if (policyName.endsWith("GUARD.RESPONSE")) {
340 logger.debug("Rule Fired: " + notification.getPolicyName());
341 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
342 assertNotNull(notification.getMessage());
343 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
344 } else if (policyName.endsWith("GUARD_PERMITTED")) {
345 logger.debug("Rule Fired: " + notification.getPolicyName());
346 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
347 assertNotNull(notification.getMessage());
348 assertTrue(notification.getMessage().startsWith("actor=SO"));
349 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
350 logger.debug("Rule Fired: " + notification.getPolicyName());
352 logger.debug("The operation timed out");
353 fail("Operation Timed Out");
354 } else if (policyName.endsWith("SO.RESPONSE")) {
355 logger.debug("Rule Fired: " + notification.getPolicyName());
356 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
357 assertNotNull(notification.getMessage());
358 assertTrue(notification.getMessage().startsWith("actor=SO"));
359 } else if (policyName.endsWith("EVENT.MANAGER")) {
360 logger.debug("Rule Fired: " + notification.getPolicyName());
361 if ("error".equals(notification.getAai().get("vserver.vserver-name"))) {
362 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
363 } else if ("getFail".equals(notification.getAai().get("vserver.vserver-name"))) {
364 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
366 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
369 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
370 logger.debug("Rule Fired: " + notification.getPolicyName());
372 logger.debug("The control loop timed out");
373 fail("Control Loop Timed Out");
375 } else if (obj instanceof SoRequest) {
376 logger.debug("\n============ SO received the request!!! ===========\n");
381 * This method is used to simulate event messages from DCAE that start the control loop (onset
382 * message) or end the control loop (abatement message).
384 * @param policy the controlLoopName comes from the policy
385 * @param requestId the requestId for this event
386 * @param status could be onset or abated
388 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
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", "dfw1lb01lb01");
396 event.getAai().put("vserver.is-closed-loop-disabled", "false");
397 event.getAai().put("vserver.prov-status", "ACTIVE");
398 event.setClosedLoopEventStatus(status);
399 kieSession.insert(event);
402 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
403 String vserverName) {
404 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
405 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
406 event.setRequestId(requestId);
407 event.setTarget("vserver.vserver-name");
408 event.setClosedLoopAlarmStart(Instant.now());
409 event.setAai(new HashMap<>());
410 event.getAai().put("vserver.vserver-name", vserverName);
411 event.setClosedLoopEventStatus(status);
412 kieSession.insert(event);
416 * This method will dump all the facts in the working memory.
418 * @param kieSession the session containing the facts
420 public void dumpFacts(KieSession kieSession) {
421 logger.debug("Fact Count: {}", kieSession.getFactCount());
422 for (FactHandle handle : kieSession.getFactHandles()) {
423 logger.debug("FACT: {}", handle);