605732c31833ded6b51bd3383e73155adc082782
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
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
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.SupportUtil.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 SupportUtil.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         SupportUtil.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                 .modelClassLoaderHash(1111));
134         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
135                 .groupId("junit.groupId")
136                 .artifactId("junit.artifactId")
137                 .topic("APPC-CL")
138                 .eventClass("org.onap.policy.appc.Request")
139                 .protocolFilter(new JsonProtocolFilter())
140                 .modelClassLoaderHash(1111));
141
142         try {
143             SupportUtil.buildAaiSim();
144
145         } catch (Exception e) {
146             logger.error("Could not create simulator", e);
147             fail("Could not create simulator");
148         }
149
150         for (TopicSink sink : noopTopics) {
151             assertTrue(sink.start());
152         }
153
154         try {
155             specifications = new SupportUtil.RuleSpec[2];
156
157             specifications[0] = new SupportUtil.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME, POLICY_SCOPE, POLICY_NAME,
158                             POLICY_VERSION, loadYaml(YAML));
159
160             specifications[1] = new SupportUtil.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME_B, POLICY_SCOPE,
161                             POLICY_NAME_B, POLICY_VERSION, loadYaml(YAML_B));
162
163             kieSession = SupportUtil.buildContainer(POLICY_VERSION, specifications);
164
165         } catch (IOException e) {
166             logger.error("Could not create kieSession", e);
167             fail("Could not create kieSession");
168         }
169     }
170
171     /**
172      * Tear down.
173      */
174     @AfterClass
175     public static void tearDown() {
176         kieSession.dispose();
177
178         PolicyEngine.manager.stop();
179         HttpServletServer.factory.destroy();
180         PolicyController.factory.shutdown();
181         TopicEndpoint.manager.shutdown();
182
183         if (saveGuardFlag == null) {
184             PolicyEngine.manager.getEnvironment().remove(GUARD_DISABLED);
185
186         } else {
187             PolicyEngine.manager.getEnvironment().setProperty(GUARD_DISABLED, saveGuardFlag);
188         }
189     }
190
191     @Test
192     public void test() throws IOException {
193
194         /*
195          * Let rules create Params objects.
196          */
197         kieSession.fireAllRules();
198
199         injectEvent(CONTROL_LOOP_NAME);
200         injectEvent(CONTROL_LOOP_NAME_B);
201
202         kieSession.fireAllRules();
203         List<Object> facts = getSessionObjects();
204         
205         // should have events for both control loops
206         assertEquals(2 * CL_OBJECTS, facts.size());
207         assertTrue(hasEvent(facts, CONTROL_LOOP_NAME));
208         assertTrue(hasEvent(facts, CONTROL_LOOP_NAME_B));
209
210         logger.info("UPDATING VERSION TO v3.0");
211         updatePolicy(YAML2, "v3.0");
212
213         /*
214          * Let rules update Params objects. The Params for the first set of rules should
215          * now be deleted and replaced with a new one, while the Params for the second set
216          * should be unchanged.
217          */
218         kieSession.fireAllRules();
219         facts = getSessionObjects();
220
221         // should only have event for second control loop + 1 Params for first control loop
222         assertEquals(CL_OBJECTS + 1, facts.size());
223         assertTrue(hasEvent(facts, CONTROL_LOOP_NAME_B));
224
225         // add event for first control loop again
226         injectEvent(CONTROL_LOOP_NAME);
227         kieSession.fireAllRules();
228
229         logger.info("UPDATING VERSION TO v4.0");
230         updatePolicy(YAML, "v4.0");
231
232         /*
233          * Let rules update Params objects. The Params for the first set of rules should
234          * now be deleted and replaced with a new one, while the Params for the second set
235          * should be unchanged.
236          */
237         kieSession.fireAllRules();
238         facts = getSessionObjects();
239
240         // should only have event for second control loop + 1 Params for first control loop
241         assertEquals(CL_OBJECTS + 1, facts.size());
242         assertTrue(hasEvent(facts, CONTROL_LOOP_NAME_B));
243
244         // add event for first control loop again
245         injectEvent(CONTROL_LOOP_NAME);
246         kieSession.fireAllRules();
247
248         logger.info("UPDATING VERSION TO v4.0 (i.e., unchanged)");
249         updatePolicy(YAML, "v4.0");
250
251         /*
252          * Let rules update Params objects. As the version (and YAML) are unchanged for
253          * either rule set, both Params objects should be unchanged.
254          */
255         kieSession.fireAllRules();
256         facts = getSessionObjects();
257
258         // should have events for both control loops
259         assertEquals(2 * CL_OBJECTS, facts.size());
260         assertTrue(hasEvent(facts, CONTROL_LOOP_NAME));
261         assertTrue(hasEvent(facts, CONTROL_LOOP_NAME_B));
262
263         /*
264          * Now we'll delete the first rule set. That won't actually have any immediate
265          * effect, so then we'll update the second rule set, which should trigger a
266          * clean-up of both.
267          */
268         SupportUtil.RuleSpec[] specs = new SupportUtil.RuleSpec[1];
269         specs[0] = specifications[1];
270
271         logger.info("UPDATING VERSION TO v5.0 - DELETED RULE SET");
272         SupportUtil.updateContainer("v5.0", specs);
273
274         specs[0] = new SupportUtil.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME_B, POLICY_SCOPE, POLICY_NAME_B,
275                         POLICY_VERSION, loadYaml(YAML));
276
277         logger.info("UPDATING VERSION TO v6.0 - UPDATED SECOND RULE SET");
278         SupportUtil.updateContainer("v6.0", specs);
279
280         kieSession.fireAllRules();
281         facts = getSessionObjects();
282
283         // only 1 Params should remain, for second rule set, but events should be gone
284         assertEquals(1, facts.size());
285         assertTrue(facts.stream().anyMatch(obj -> obj.toString().startsWith("Params( ")));
286     }
287
288     /**
289      * Updates the policy, changing the YAML associated with the first rule set.
290      *
291      * @param yamlFile name of the YAML file
292      * @param policyVersion policy version
293      * @throws IOException if an error occurs
294      */
295     private static void updatePolicy(String yamlFile, String policyVersion) throws IOException {
296
297         specifications[0] = new SupportUtil.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME, POLICY_SCOPE, POLICY_NAME,
298                         policyVersion, loadYaml(yamlFile));
299
300         /*
301          * Update the policy within the container.
302          */
303         SupportUtil.updateContainer(policyVersion, specifications);
304     }
305
306     /**
307      * Loads a YAML file and URL-encodes it.
308      *
309      * @param yamlFile name of the YAML file
310      * @return the contents of the specified file, URL-encoded
311      * @throws UnsupportedEncodingException if an error occurs
312      */
313     private static String loadYaml(String yamlFile) throws UnsupportedEncodingException {
314         Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml(yamlFile);
315         assertNotNull(pair);
316         assertNotNull(pair.first);
317         assertNotNull(pair.first.getControlLoop());
318         assertNotNull(pair.first.getControlLoop().getControlLoopName());
319         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
320
321         return URLEncoder.encode(pair.second, "UTF-8");
322     }
323
324     /**
325      * Gets the session objects.
326      *
327      * @return the session objects
328      */
329     private static List<Object> getSessionObjects() {
330         // sort the objects so we know the order
331         LinkedList<Object> lst = new LinkedList<>(kieSession.getObjects());
332         lst.sort((left, right) -> left.toString().compareTo(right.toString()));
333
334         lst.forEach(obj -> logger.info("obj={}", obj));
335
336         return lst;
337     }
338
339     /**
340      * Injects an ONSET event into the rule engine.
341      *
342      * @param controlLoopName the control loop name
343      */
344     private void injectEvent(String controlLoopName) {
345         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
346
347         event.setClosedLoopControlName(controlLoopName);
348
349         UUID reqid = UUID.randomUUID();
350         event.setRequestId(reqid);
351
352         event.setTarget("generic-vnf.vnf-id");
353         event.setClosedLoopAlarmStart(Instant.now());
354         event.setAai(new HashMap<>());
355         event.getAai().put("generic-vnf.vnf-id", "vnf-" + reqid.toString());
356         event.getAai().put(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED, "false");
357         event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET);
358
359         kieSession.insert(event);
360     }
361
362     /**
363      * Determines if the facts contain an event for the given control loop.
364      * 
365      * @param facts session facts to be checked
366      * @param controlLoopName name of the control loop of interest
367      * @return {@code true} if the facts contain an event for the given control loop,
368      *         {@code false} otherwise
369      */
370     private boolean hasEvent(List<Object> facts, String controlLoopName) {
371         return (facts.stream().anyMatch(obj -> obj instanceof VirtualControlLoopEvent
372                         && controlLoopName.equals(((VirtualControlLoopEvent) obj).getClosedLoopControlName())));
373     }
374 }