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;
35 import org.junit.AfterClass;
36 import org.junit.BeforeClass;
37 import org.junit.Test;
38 import org.kie.api.runtime.KieSession;
39 import org.kie.api.runtime.rule.FactHandle;
40 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
41 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
42 import org.onap.policy.common.endpoints.event.comm.TopicListener;
43 import org.onap.policy.common.endpoints.event.comm.TopicSink;
44 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
45 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
46 import org.onap.policy.controlloop.ControlLoopEventStatus;
47 import org.onap.policy.controlloop.ControlLoopNotificationType;
48 import org.onap.policy.controlloop.VirtualControlLoopEvent;
49 import org.onap.policy.controlloop.VirtualControlLoopNotification;
50 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
51 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
52 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
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 SupportUtil.Pair<ControlLoopPolicy, String> pair;
69 private UUID requestId;
72 /* Set environment properties */
73 SupportUtil.setAaiProps();
74 SupportUtil.setSoProps();
75 SupportUtil.setGuardProps();
76 SupportUtil.setPuProp();
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 = TopicEndpointManager.getManager().addTopicSinks(noopSinkProperties);
95 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
96 .groupId("junit.groupId")
97 .artifactId("junit.artifactId")
98 .topic("POLICY-CL-MGT")
99 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
100 .protocolFilter(new JsonProtocolFilter())
101 .modelClassLoaderHash(1111));
104 SupportUtil.buildAaiSim();
105 SupportUtil.buildSoSim();
106 SupportUtil.buildGuardSim();
107 } catch (Exception e) {
108 fail(e.getMessage());
112 * Start the kie session
115 kieSession = startSession(
116 "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
117 + "src/main/resources/__closedLoopControlName__.drl",
118 "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml", "type=operational", "CL_vDNS", "v2.0");
119 } catch (IOException e) {
121 logger.debug("Could not create kieSession");
122 fail("Could not create kieSession");
127 * Tear down the simulator.
130 public static void tearDownSimulator() {
133 * Gracefully shut down the kie session
135 kieSession.dispose();
137 PolicyEngine.manager.stop();
138 HttpServletServerFactoryInstance.getServerFactory().destroy();
139 PolicyController.factory.shutdown();
140 TopicEndpointManager.getManager().shutdown();
144 public void successTest() {
147 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
148 * to be pulled from the queue
150 for (TopicSink sink : noopTopics) {
151 assertTrue(sink.start());
156 * Create a unique requestId
158 requestId = UUID.randomUUID();
161 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
164 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET);
166 kieSession.fireUntilHalt();
168 // allow object clean-up
169 kieSession.fireAllRules();
172 * The only fact in memory should be Params
174 assertEquals(1, kieSession.getFactCount());
177 * Print what's left in memory
179 dumpFacts(kieSession);
183 public void namedQueryFailTest() {
186 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
187 * to be pulled from the queue
189 for (TopicSink sink : noopTopics) {
190 assertTrue(sink.start());
195 * Create a unique requestId
197 requestId = UUID.randomUUID();
200 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
203 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error");
205 kieSession.fireUntilHalt();
207 // allow object clean-up
208 kieSession.fireAllRules();
211 * The only fact in memory should be Params
213 assertEquals(1, kieSession.getFactCount());
216 * Print what's left in memory
218 dumpFacts(kieSession);
222 public void aaiGetFailTest() {
225 * Allows the PolicyEngine to callback to this object to notify that there is an event ready
226 * to be pulled from the queue
228 for (TopicSink sink : noopTopics) {
229 assertTrue(sink.start());
234 * Create a unique requestId
236 requestId = UUID.randomUUID();
239 * Simulate an onset event the policy engine will receive from DCAE to kick off processing
242 sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail");
245 kieSession.fireUntilHalt();
247 // allow object clean-up
248 kieSession.fireAllRules();
250 } catch (Exception e) {
252 logger.warn(e.toString());
253 fail(e.getMessage());
258 * The only fact in memory should be Params
260 assertEquals(1, kieSession.getFactCount());
263 * Print what's left in memory
265 dumpFacts(kieSession);
269 * This method will start a kie session and instantiate the Policy Engine.
271 * @param droolsTemplate the DRL rules file
272 * @param yamlFile the yaml file containing the policies
273 * @param policyScope scope for policy
274 * @param policyName name of the policy
275 * @param policyVersion version of the policy
276 * @return the kieSession to be used to insert facts
277 * @throws IOException IO Exception
279 private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
280 String policyName, String policyVersion) throws IOException {
283 * Load policies from yaml
285 pair = SupportUtil.loadYaml(yamlFile);
287 assertNotNull(pair.first);
288 assertNotNull(pair.first.getControlLoop());
289 assertNotNull(pair.first.getControlLoop().getControlLoopName());
290 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
293 * Construct a kie session
295 final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate,
296 pair.first.getControlLoop().getControlLoopName(),
297 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
300 * Retrieve the Policy Engine
303 logger.debug("============");
304 logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
305 logger.debug("============");
313 * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
316 public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
318 * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
322 if ("POLICY-CL-MGT".equals(topic)) {
323 obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
324 org.onap.policy.controlloop.VirtualControlLoopNotification.class);
327 if (obj instanceof VirtualControlLoopNotification) {
328 VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
329 String policyName = notification.getPolicyName();
330 if (policyName.endsWith("EVENT")) {
331 logger.debug("Rule Fired: " + notification.getPolicyName());
332 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
333 } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
334 logger.debug("Rule Fired: " + notification.getPolicyName());
335 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
336 assertNotNull(notification.getMessage());
337 assertTrue(notification.getMessage().startsWith("Sending guard query"));
338 } else if (policyName.endsWith("GUARD.RESPONSE")) {
339 logger.debug("Rule Fired: " + notification.getPolicyName());
340 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
341 assertNotNull(notification.getMessage());
342 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
343 } else if (policyName.endsWith("GUARD_PERMITTED")) {
344 logger.debug("Rule Fired: " + notification.getPolicyName());
345 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
346 assertNotNull(notification.getMessage());
347 assertTrue(notification.getMessage().startsWith("actor=SO"));
348 } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
349 logger.debug("Rule Fired: " + notification.getPolicyName());
351 logger.debug("The operation timed out");
352 fail("Operation Timed Out");
353 } else if (policyName.endsWith("SO.RESPONSE")) {
354 logger.debug("Rule Fired: " + notification.getPolicyName());
355 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
356 assertNotNull(notification.getMessage());
357 assertTrue(notification.getMessage().startsWith("actor=SO"));
358 } else if (policyName.endsWith("EVENT.MANAGER")) {
359 logger.debug("Rule Fired: " + notification.getPolicyName());
360 if ("error".equals(notification.getAai().get("vserver.vserver-name"))) {
361 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
362 } else if ("getFail".equals(notification.getAai().get("vserver.vserver-name"))) {
363 assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification());
365 assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
368 } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
369 logger.debug("Rule Fired: " + notification.getPolicyName());
371 logger.debug("The control loop timed out");
372 fail("Control Loop Timed Out");
374 } else if (obj instanceof SoRequest) {
375 logger.debug("\n============ SO received the request!!! ===========\n");
380 * This method is used to simulate event messages from DCAE that start the control loop (onset
381 * message) or end the control loop (abatement message).
383 * @param policy the controlLoopName comes from the policy
384 * @param requestId the requestId for this event
385 * @param status could be onset or abated
387 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) {
388 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
389 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
390 event.setRequestId(requestId);
391 event.setTarget("vserver.vserver-name");
392 event.setClosedLoopAlarmStart(Instant.now());
393 event.setAai(new HashMap<>());
394 event.getAai().put("vserver.vserver-name", "dfw1lb01lb01");
395 event.getAai().put("vserver.is-closed-loop-disabled", "false");
396 event.getAai().put("vserver.prov-status", "ACTIVE");
397 event.setClosedLoopEventStatus(status);
398 kieSession.insert(event);
401 protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status,
402 String vserverName) {
403 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
404 event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
405 event.setRequestId(requestId);
406 event.setTarget("vserver.vserver-name");
407 event.setClosedLoopAlarmStart(Instant.now());
408 event.setAai(new HashMap<>());
409 event.getAai().put("vserver.vserver-name", vserverName);
410 event.setClosedLoopEventStatus(status);
411 kieSession.insert(event);
415 * This method will dump all the facts in the working memory.
417 * @param kieSession the session containing the facts
419 public void dumpFacts(KieSession kieSession) {
420 logger.debug("Fact Count: {}", kieSession.getFactCount());
421 for (FactHandle handle : kieSession.getFactHandles()) {
422 logger.debug("FACT: {}", handle);