ef5fac693be67dec0f0469adedd451ad8e45dd45
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
4  * ================================================================================
5  * Copyright (C) 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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.policy.template.demo.clc;
22
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;
27
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.TopicEndpoint;
42 import org.onap.policy.common.endpoints.event.comm.TopicSink;
43 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
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.clc.Util.Pair;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
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.
63  */
64 public class ControlLoopEventCleanupTest {
65     private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventCleanupTest.class);
66
67     /**
68      * Number of objects per control loop, including the Params object.
69      */
70     private static int CL_OBJECTS = 7;
71
72     private static final String YAML = "src/test/resources/yaml/policy_ControlLoop_EventCleanup-test.yaml";
73
74     /**
75      * YAML to be used when the first rule set is updated.
76      */
77     private static final String YAML2 = "src/test/resources/yaml/policy_ControlLoop_EventCleanup-test2.yaml";
78
79     private static final String POLICY_VERSION = "v2.0";
80
81     private static final String POLICY_NAME = "CL_CleanupTest";
82
83     private static final String POLICY_SCOPE = "type=operational";
84
85     private static final String CONTROL_LOOP_NAME = "ControlLoop-Event-Cleanup-Test";
86
87     private static final String DROOLS_TEMPLATE = "src/main/resources/__closedLoopControlName__.drl";
88
89     // values specific to the second copy of the rules
90
91     private static final String YAML_B = "src/test/resources/yaml/policy_ControlLoop_EventCleanup-test-B.yaml";
92     private static final String POLICY_NAME_B = "CL_CleanupTest_B";
93     private static final String CONTROL_LOOP_NAME_B = "ControlLoop-Event-Cleanup-Test-B";
94
95     private static final String GUARD_DISABLED = "guard.disabled";
96
97     private static String saveGuardFlag;
98
99     private static KieSession kieSession;
100     private static Util.RuleSpec[] specifications;
101
102     /**
103      * Setup the simulator.
104      */
105     @BeforeClass
106     public static void setUpSimulator() {
107         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
108
109         saveGuardFlag = PolicyEngine.manager.getEnvironmentProperty(GUARD_DISABLED);
110         PolicyEngine.manager.getEnvironment().setProperty(GUARD_DISABLED, "true");
111
112         Util.setAaiProps();
113
114         PolicyEngine.manager.configure(new Properties());
115         assertTrue(PolicyEngine.manager.start());
116         Properties noopSinkProperties = new Properties();
117         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT");
118         noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response");
119         noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson",
120                         "org.onap.policy.appc.util.Serialization,gsonPretty");
121         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
122                         "org.onap.policy.controlloop.VirtualControlLoopNotification");
123         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
124                         "org.onap.policy.controlloop.util.Serialization,gsonPretty");
125         final List<TopicSink> noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
126
127         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
128                 .groupId("junit.groupId")
129                 .artifactId("junit.artifactId")
130                 .topic("POLICY-CL-MGT")
131                 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
132                 .protocolFilter(new JsonProtocolFilter())
133                 .customGsonCoder(null)
134                 .customJacksonCoder(null)
135                 .modelClassLoaderHash(1111));
136         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
137                 .groupId("junit.groupId")
138                 .artifactId("junit.artifactId")
139                 .topic("APPC-CL")
140                 .eventClass("org.onap.policy.appc.Request")
141                 .protocolFilter(new JsonProtocolFilter())
142                 .customGsonCoder(null)
143                 .customJacksonCoder(null)
144                 .modelClassLoaderHash(1111));
145
146         try {
147             Util.buildAaiSim();
148
149         } catch (Exception e) {
150             logger.error("Could not create simulator", e);
151             fail("Could not create simulator");
152         }
153
154         for (TopicSink sink : noopTopics) {
155             assertTrue(sink.start());
156         }
157
158         try {
159             specifications = new Util.RuleSpec[2];
160
161             specifications[0] = new Util.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME, POLICY_SCOPE, POLICY_NAME,
162                             POLICY_VERSION, loadYaml(YAML));
163
164             specifications[1] = new Util.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME_B, POLICY_SCOPE, POLICY_NAME_B,
165                             POLICY_VERSION, loadYaml(YAML_B));
166
167             kieSession = Util.buildContainer(POLICY_VERSION, specifications);
168
169         } catch (IOException e) {
170             logger.error("Could not create kieSession", e);
171             fail("Could not create kieSession");
172         }
173     }
174
175     /**
176      * Tear down.
177      */
178     @AfterClass
179     public static void tearDown() {
180         kieSession.dispose();
181
182         PolicyEngine.manager.stop();
183         HttpServletServer.factory.destroy();
184         PolicyController.factory.shutdown();
185         TopicEndpoint.manager.shutdown();
186
187         if (saveGuardFlag == null) {
188             PolicyEngine.manager.getEnvironment().remove(GUARD_DISABLED);
189
190         } else {
191             PolicyEngine.manager.getEnvironment().setProperty(GUARD_DISABLED, saveGuardFlag);
192         }
193     }
194
195     @Test
196     public void test() throws IOException {
197
198         /*
199          * Let rules create Params objects.
200          */
201         kieSession.fireAllRules();
202
203         injectEvent(CONTROL_LOOP_NAME);
204         injectEvent(CONTROL_LOOP_NAME_B);
205
206         kieSession.fireAllRules();
207         List<Object> facts = getSessionObjects();
208         
209         // should have events for both control loops
210         assertEquals(2 * CL_OBJECTS, facts.size());
211         assertTrue(hasEvent(facts, CONTROL_LOOP_NAME));
212         assertTrue(hasEvent(facts, CONTROL_LOOP_NAME_B));
213
214         logger.info("UPDATING VERSION TO v3.0");
215         updatePolicy(YAML2, "v3.0");
216
217         /*
218          * Let rules update Params objects. The Params for the first set of rules should
219          * now be deleted and replaced with a new one, while the Params for the second set
220          * should be unchanged.
221          */
222         kieSession.fireAllRules();
223         facts = getSessionObjects();
224
225         // should only have event for second control loop + 1 Params for first control loop
226         assertEquals(CL_OBJECTS + 1, facts.size());
227         assertTrue(hasEvent(facts, CONTROL_LOOP_NAME_B));
228
229         // add event for first control loop again
230         injectEvent(CONTROL_LOOP_NAME);
231         kieSession.fireAllRules();
232
233         logger.info("UPDATING VERSION TO v4.0");
234         updatePolicy(YAML, "v4.0");
235
236         /*
237          * Let rules update Params objects. The Params for the first set of rules should
238          * now be deleted and replaced with a new one, while the Params for the second set
239          * should be unchanged.
240          */
241         kieSession.fireAllRules();
242         facts = getSessionObjects();
243
244         // should only have event for second control loop + 1 Params for first control loop
245         assertEquals(CL_OBJECTS + 1, facts.size());
246         assertTrue(hasEvent(facts, CONTROL_LOOP_NAME_B));
247
248         // add event for first control loop again
249         injectEvent(CONTROL_LOOP_NAME);
250         kieSession.fireAllRules();
251
252         logger.info("UPDATING VERSION TO v4.0 (i.e., unchanged)");
253         updatePolicy(YAML, "v4.0");
254
255         /*
256          * Let rules update Params objects. As the version (and YAML) are unchanged for
257          * either rule set, both Params objects should be unchanged.
258          */
259         kieSession.fireAllRules();
260         facts = getSessionObjects();
261
262         // should have events for both control loops
263         assertEquals(2 * CL_OBJECTS, facts.size());
264         assertTrue(hasEvent(facts, CONTROL_LOOP_NAME));
265         assertTrue(hasEvent(facts, CONTROL_LOOP_NAME_B));
266
267         /*
268          * Now we'll delete the first rule set. That won't actually have any immediate
269          * effect, so then we'll update the second rule set, which should trigger a
270          * clean-up of both.
271          */
272         Util.RuleSpec[] specs = new Util.RuleSpec[1];
273         specs[0] = specifications[1];
274
275         logger.info("UPDATING VERSION TO v5.0 - DELETED RULE SET");
276         Util.updateContainer("v5.0", specs);
277
278         specs[0] = new Util.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME_B, POLICY_SCOPE, POLICY_NAME_B, POLICY_VERSION,
279                         loadYaml(YAML));
280
281         logger.info("UPDATING VERSION TO v6.0 - UPDATED SECOND RULE SET");
282         Util.updateContainer("v6.0", specs);
283
284         kieSession.fireAllRules();
285         facts = getSessionObjects();
286
287         // only 1 Params should remain, for second rule set, but events should be gone
288         assertEquals(1, facts.size());
289         assertTrue(facts.stream().anyMatch(obj -> obj.toString().startsWith("Params( ")));
290     }
291
292     /**
293      * Updates the policy, changing the YAML associated with the first rule set.
294      *
295      * @param yamlFile name of the YAML file
296      * @param policyVersion policy version
297      * @throws IOException if an error occurs
298      */
299     private static void updatePolicy(String yamlFile, String policyVersion) throws IOException {
300
301         specifications[0] = new Util.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME, POLICY_SCOPE, POLICY_NAME,
302                         policyVersion, loadYaml(yamlFile));
303
304         /*
305          * Update the policy within the container.
306          */
307         Util.updateContainer(policyVersion, specifications);
308     }
309
310     /**
311      * Loads a YAML file and URL-encodes it.
312      *
313      * @param yamlFile name of the YAML file
314      * @return the contents of the specified file, URL-encoded
315      * @throws UnsupportedEncodingException if an error occurs
316      */
317     private static String loadYaml(String yamlFile) throws UnsupportedEncodingException {
318         Pair<ControlLoopPolicy, String> pair = Util.loadYaml(yamlFile);
319         assertNotNull(pair);
320         assertNotNull(pair.first);
321         assertNotNull(pair.first.getControlLoop());
322         assertNotNull(pair.first.getControlLoop().getControlLoopName());
323         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
324
325         return URLEncoder.encode(pair.second, "UTF-8");
326     }
327
328     /**
329      * Gets the session objects.
330      *
331      * @return the session objects
332      */
333     private static List<Object> getSessionObjects() {
334         // sort the objects so we know the order
335         LinkedList<Object> lst = new LinkedList<>(kieSession.getObjects());
336         lst.sort((left, right) -> left.toString().compareTo(right.toString()));
337
338         lst.forEach(obj -> logger.info("obj={}", obj));
339
340         return lst;
341     }
342
343     /**
344      * Injects an ONSET event into the rule engine.
345      *
346      * @param controlLoopName the control loop name
347      */
348     private void injectEvent(String controlLoopName) {
349         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
350
351         event.setClosedLoopControlName(controlLoopName);
352
353         UUID reqid = UUID.randomUUID();
354         event.setRequestId(reqid);
355
356         event.setTarget("generic-vnf.vnf-id");
357         event.setClosedLoopAlarmStart(Instant.now());
358         event.setAai(new HashMap<>());
359         event.getAai().put("generic-vnf.vnf-id", "vnf-" + reqid.toString());
360         event.getAai().put(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED, "false");
361         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
362
363         kieSession.insert(event);
364     }
365
366     /**
367      * Determines if the facts contain an event for the given control loop.
368      * 
369      * @param facts session facts to be checked
370      * @param controlLoopName name of the control loop of interest
371      * @return {@code true} if the facts contain an event for the given control loop,
372      *         {@code false} otherwise
373      */
374     private boolean hasEvent(List<Object> facts, String controlLoopName) {
375         return (facts.stream().anyMatch(obj -> obj instanceof VirtualControlLoopEvent
376                         && controlLoopName.equals(((VirtualControlLoopEvent) obj).getClosedLoopControlName())));
377     }
378 }