2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018-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.io.UnsupportedEncodingException;
30 import java.net.URLEncoder;
31 import java.time.Instant;
32 import java.util.HashMap;
33 import java.util.LinkedList;
34 import java.util.List;
35 import java.util.Properties;
36 import java.util.UUID;
37 import org.junit.AfterClass;
38 import org.junit.BeforeClass;
39 import org.junit.Test;
40 import org.kie.api.runtime.KieSession;
41 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
42 import org.onap.policy.common.endpoints.event.comm.TopicSink;
43 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
44 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
45 import org.onap.policy.controlloop.ControlLoopEventStatus;
46 import org.onap.policy.controlloop.VirtualControlLoopEvent;
47 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager;
48 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
49 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
50 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
51 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
52 import org.onap.policy.drools.system.PolicyController;
53 import org.onap.policy.drools.system.PolicyEngine;
54 import org.onap.policy.drools.utils.logging.LoggerUtil;
55 import org.onap.policy.template.demo.SupportUtil.Pair;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
60 * Verifies that event objects are cleaned up when rules are updated. This loads
61 * <b>two</b> copies of the rule set into a single policy to ensure that the two copies
62 * interact appropriately with each other's event objects.
64 public class ControlLoopEventCleanupTest {
65 private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventCleanupTest.class);
68 * Number of objects per control loop, including the Params object.
70 private static int CL_OBJECTS = 7;
72 private static final String YAML = "src/test/resources/yaml/policy_ControlLoop_EventCleanup-test.yaml";
75 * YAML to be used when the first rule set is updated.
77 private static final String YAML2 = "src/test/resources/yaml/policy_ControlLoop_EventCleanup-test2.yaml";
79 private static final String POLICY_VERSION = "v2.0";
81 private static final String POLICY_NAME = "CL_CleanupTest";
83 private static final String POLICY_SCOPE = "type=operational";
85 private static final String CONTROL_LOOP_NAME = "ControlLoop-Event-Cleanup-Test";
87 private static final String DROOLS_TEMPLATE = "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
88 + "src/main/resources/__closedLoopControlName__.drl";
90 // values specific to the second copy of the rules
92 private static final String YAML_B = "src/test/resources/yaml/policy_ControlLoop_EventCleanup-test-B.yaml";
93 private static final String POLICY_NAME_B = "CL_CleanupTest_B";
94 private static final String CONTROL_LOOP_NAME_B = "ControlLoop-Event-Cleanup-Test-B";
96 private static final String GUARD_DISABLED = "guard.disabled";
98 private static String saveGuardFlag;
100 private static KieSession kieSession;
101 private static SupportUtil.RuleSpec[] specifications;
104 * Setup the simulator.
107 public static void setUpSimulator() {
108 LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
110 saveGuardFlag = PolicyEngine.manager.getEnvironmentProperty(GUARD_DISABLED);
111 PolicyEngine.manager.getEnvironment().setProperty(GUARD_DISABLED, "true");
113 SupportUtil.setAaiProps();
115 PolicyEngine.manager.configure(new Properties());
116 assertTrue(PolicyEngine.manager.start());
117 Properties noopSinkProperties = new Properties();
118 noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT");
119 noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response");
120 noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson",
121 "org.onap.policy.appc.util.Serialization,gsonPretty");
122 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
123 "org.onap.policy.controlloop.VirtualControlLoopNotification");
124 noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
125 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
126 final List<TopicSink> noopTopics = TopicEndpointManager.getManager().addTopicSinks(noopSinkProperties);
128 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
129 .groupId("junit.groupId")
130 .artifactId("junit.artifactId")
131 .topic("POLICY-CL-MGT")
132 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
133 .protocolFilter(new JsonProtocolFilter())
134 .modelClassLoaderHash(1111));
135 EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
136 .groupId("junit.groupId")
137 .artifactId("junit.artifactId")
139 .eventClass("org.onap.policy.appc.Request")
140 .protocolFilter(new JsonProtocolFilter())
141 .modelClassLoaderHash(1111));
144 SupportUtil.buildAaiSim();
146 } catch (Exception e) {
147 logger.error("Could not create simulator", e);
148 fail("Could not create simulator");
151 for (TopicSink sink : noopTopics) {
152 assertTrue(sink.start());
156 specifications = new SupportUtil.RuleSpec[2];
158 specifications[0] = new SupportUtil.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME, POLICY_SCOPE, POLICY_NAME,
159 POLICY_VERSION, loadYaml(YAML));
161 specifications[1] = new SupportUtil.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME_B, POLICY_SCOPE,
162 POLICY_NAME_B, POLICY_VERSION, loadYaml(YAML_B));
164 kieSession = SupportUtil.buildContainer(POLICY_VERSION, specifications);
166 } catch (IOException e) {
167 logger.error("Could not create kieSession", e);
168 fail("Could not create kieSession");
176 public static void tearDown() {
177 kieSession.dispose();
179 PolicyEngine.manager.stop();
180 HttpServletServerFactoryInstance.getServerFactory().destroy();
181 PolicyController.factory.shutdown();
182 TopicEndpointManager.getManager().shutdown();
184 if (saveGuardFlag == null) {
185 PolicyEngine.manager.getEnvironment().remove(GUARD_DISABLED);
188 PolicyEngine.manager.getEnvironment().setProperty(GUARD_DISABLED, saveGuardFlag);
193 public void test() throws IOException {
196 * Let rules create Params objects.
198 kieSession.fireAllRules();
200 injectEvent(CONTROL_LOOP_NAME);
201 injectEvent(CONTROL_LOOP_NAME_B);
203 kieSession.fireAllRules();
204 List<Object> facts = getSessionObjects();
206 // should have events for both control loops
207 assertEquals(2 * CL_OBJECTS, facts.size());
208 assertTrue(hasEvent(facts, CONTROL_LOOP_NAME));
209 assertTrue(hasEvent(facts, CONTROL_LOOP_NAME_B));
211 logger.info("UPDATING VERSION TO v3.0");
212 updatePolicy(YAML2, "v3.0");
215 * Let rules update Params objects. The Params for the first set of rules should
216 * now be deleted and replaced with a new one, while the Params for the second set
217 * should be unchanged.
219 kieSession.fireAllRules();
220 facts = getSessionObjects();
222 // should only have event for second control loop + 1 Params for first control loop
223 assertEquals(CL_OBJECTS + 1, facts.size());
224 assertTrue(hasEvent(facts, CONTROL_LOOP_NAME_B));
226 // add event for first control loop again
227 injectEvent(CONTROL_LOOP_NAME);
228 kieSession.fireAllRules();
230 logger.info("UPDATING VERSION TO v4.0");
231 updatePolicy(YAML, "v4.0");
234 * Let rules update Params objects. The Params for the first set of rules should
235 * now be deleted and replaced with a new one, while the Params for the second set
236 * should be unchanged.
238 kieSession.fireAllRules();
239 facts = getSessionObjects();
241 // should only have event for second control loop + 1 Params for first control loop
242 assertEquals(CL_OBJECTS + 1, facts.size());
243 assertTrue(hasEvent(facts, CONTROL_LOOP_NAME_B));
245 // add event for first control loop again
246 injectEvent(CONTROL_LOOP_NAME);
247 kieSession.fireAllRules();
249 logger.info("UPDATING VERSION TO v4.0 (i.e., unchanged)");
250 updatePolicy(YAML, "v4.0");
253 * Let rules update Params objects. As the version (and YAML) are unchanged for
254 * either rule set, both Params objects should be unchanged.
256 kieSession.fireAllRules();
257 facts = getSessionObjects();
259 // should have events for both control loops
260 assertEquals(2 * CL_OBJECTS, facts.size());
261 assertTrue(hasEvent(facts, CONTROL_LOOP_NAME));
262 assertTrue(hasEvent(facts, CONTROL_LOOP_NAME_B));
265 * Now we'll delete the first rule set. That won't actually have any immediate
266 * effect, so then we'll update the second rule set, which should trigger a
269 SupportUtil.RuleSpec[] specs = new SupportUtil.RuleSpec[1];
270 specs[0] = specifications[1];
272 logger.info("UPDATING VERSION TO v5.0 - DELETED RULE SET");
273 SupportUtil.updateContainer("v5.0", specs);
275 specs[0] = new SupportUtil.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME_B, POLICY_SCOPE, POLICY_NAME_B,
276 POLICY_VERSION, loadYaml(YAML));
278 logger.info("UPDATING VERSION TO v6.0 - UPDATED SECOND RULE SET");
279 SupportUtil.updateContainer("v6.0", specs);
281 kieSession.fireAllRules();
282 facts = getSessionObjects();
284 // only 1 Params should remain, for second rule set, but events should be gone
285 assertEquals(1, facts.size());
286 assertTrue(facts.stream().anyMatch(obj -> obj.toString().startsWith("Params( ")));
290 * Updates the policy, changing the YAML associated with the first rule set.
292 * @param yamlFile name of the YAML file
293 * @param policyVersion policy version
294 * @throws IOException if an error occurs
296 private static void updatePolicy(String yamlFile, String policyVersion) throws IOException {
298 specifications[0] = new SupportUtil.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME, POLICY_SCOPE, POLICY_NAME,
299 policyVersion, loadYaml(yamlFile));
302 * Update the policy within the container.
304 SupportUtil.updateContainer(policyVersion, specifications);
308 * Loads a YAML file and URL-encodes it.
310 * @param yamlFile name of the YAML file
311 * @return the contents of the specified file, URL-encoded
312 * @throws UnsupportedEncodingException if an error occurs
314 private static String loadYaml(String yamlFile) throws UnsupportedEncodingException {
315 Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml(yamlFile);
317 assertNotNull(pair.first);
318 assertNotNull(pair.first.getControlLoop());
319 assertNotNull(pair.first.getControlLoop().getControlLoopName());
320 assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
322 return URLEncoder.encode(pair.second, "UTF-8");
326 * Gets the session objects.
328 * @return the session objects
330 private static List<Object> getSessionObjects() {
331 // sort the objects so we know the order
332 LinkedList<Object> lst = new LinkedList<>(kieSession.getObjects());
333 lst.sort((left, right) -> left.toString().compareTo(right.toString()));
335 lst.forEach(obj -> logger.info("obj={}", obj));
341 * Injects an ONSET event into the rule engine.
343 * @param controlLoopName the control loop name
345 private void injectEvent(String controlLoopName) {
346 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
348 event.setClosedLoopControlName(controlLoopName);
350 UUID reqid = UUID.randomUUID();
351 event.setRequestId(reqid);
353 event.setTarget("generic-vnf.vnf-id");
354 event.setClosedLoopAlarmStart(Instant.now());
355 event.setAai(new HashMap<>());
356 event.getAai().put("generic-vnf.vnf-id", "vnf-" + reqid.toString());
357 event.getAai().put(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED, "false");
358 event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
360 kieSession.insert(event);
364 * Determines if the facts contain an event for the given control loop.
366 * @param facts session facts to be checked
367 * @param controlLoopName name of the control loop of interest
368 * @return {@code true} if the facts contain an event for the given control loop,
369 * {@code false} otherwise
371 private boolean hasEvent(List<Object> facts, String controlLoopName) {
372 return (facts.stream().anyMatch(obj -> obj instanceof VirtualControlLoopEvent
373 && controlLoopName.equals(((VirtualControlLoopEvent) obj).getClosedLoopControlName())));