37e139074536174890cdc06cde26868bf888b806
[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;
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.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 = "../archetype-cl-amsterdam/src/main/resources/archetype-resources/"
88                     + "src/main/resources/__closedLoopControlName__.drl";
89
90     // values specific to the second copy of the rules
91
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";
95
96     private static final String GUARD_DISABLED = "guard.disabled";
97
98     private static String saveGuardFlag;
99
100     private static KieSession kieSession;
101     private static SupportUtil.RuleSpec[] specifications;
102
103     /**
104      * Setup the simulator.
105      */
106     @BeforeClass
107     public static void setUpSimulator() {
108         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO");
109
110         saveGuardFlag = PolicyEngine.manager.getEnvironmentProperty(GUARD_DISABLED);
111         PolicyEngine.manager.getEnvironment().setProperty(GUARD_DISABLED, "true");
112
113         SupportUtil.setAaiProps();
114
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 = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
127
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")
138                 .topic("APPC-CL")
139                 .eventClass("org.onap.policy.appc.Request")
140                 .protocolFilter(new JsonProtocolFilter())
141                 .modelClassLoaderHash(1111));
142
143         try {
144             SupportUtil.buildAaiSim();
145
146         } catch (Exception e) {
147             logger.error("Could not create simulator", e);
148             fail("Could not create simulator");
149         }
150
151         for (TopicSink sink : noopTopics) {
152             assertTrue(sink.start());
153         }
154
155         try {
156             specifications = new SupportUtil.RuleSpec[2];
157
158             specifications[0] = new SupportUtil.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME, POLICY_SCOPE, POLICY_NAME,
159                             POLICY_VERSION, loadYaml(YAML));
160
161             specifications[1] = new SupportUtil.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME_B, POLICY_SCOPE,
162                             POLICY_NAME_B, POLICY_VERSION, loadYaml(YAML_B));
163
164             kieSession = SupportUtil.buildContainer(POLICY_VERSION, specifications);
165
166         } catch (IOException e) {
167             logger.error("Could not create kieSession", e);
168             fail("Could not create kieSession");
169         }
170     }
171
172     /**
173      * Tear down.
174      */
175     @AfterClass
176     public static void tearDown() {
177         kieSession.dispose();
178
179         PolicyEngine.manager.stop();
180         HttpServletServer.factory.destroy();
181         PolicyController.factory.shutdown();
182         TopicEndpoint.manager.shutdown();
183
184         if (saveGuardFlag == null) {
185             PolicyEngine.manager.getEnvironment().remove(GUARD_DISABLED);
186
187         } else {
188             PolicyEngine.manager.getEnvironment().setProperty(GUARD_DISABLED, saveGuardFlag);
189         }
190     }
191
192     @Test
193     public void test() throws IOException {
194
195         /*
196          * Let rules create Params objects.
197          */
198         kieSession.fireAllRules();
199
200         injectEvent(CONTROL_LOOP_NAME);
201         injectEvent(CONTROL_LOOP_NAME_B);
202
203         kieSession.fireAllRules();
204         List<Object> facts = getSessionObjects();
205         
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));
210
211         logger.info("UPDATING VERSION TO v3.0");
212         updatePolicy(YAML2, "v3.0");
213
214         /*
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.
218          */
219         kieSession.fireAllRules();
220         facts = getSessionObjects();
221
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));
225
226         // add event for first control loop again
227         injectEvent(CONTROL_LOOP_NAME);
228         kieSession.fireAllRules();
229
230         logger.info("UPDATING VERSION TO v4.0");
231         updatePolicy(YAML, "v4.0");
232
233         /*
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.
237          */
238         kieSession.fireAllRules();
239         facts = getSessionObjects();
240
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));
244
245         // add event for first control loop again
246         injectEvent(CONTROL_LOOP_NAME);
247         kieSession.fireAllRules();
248
249         logger.info("UPDATING VERSION TO v4.0 (i.e., unchanged)");
250         updatePolicy(YAML, "v4.0");
251
252         /*
253          * Let rules update Params objects. As the version (and YAML) are unchanged for
254          * either rule set, both Params objects should be unchanged.
255          */
256         kieSession.fireAllRules();
257         facts = getSessionObjects();
258
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));
263
264         /*
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
267          * clean-up of both.
268          */
269         SupportUtil.RuleSpec[] specs = new SupportUtil.RuleSpec[1];
270         specs[0] = specifications[1];
271
272         logger.info("UPDATING VERSION TO v5.0 - DELETED RULE SET");
273         SupportUtil.updateContainer("v5.0", specs);
274
275         specs[0] = new SupportUtil.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME_B, POLICY_SCOPE, POLICY_NAME_B,
276                 POLICY_VERSION, loadYaml(YAML));
277
278         logger.info("UPDATING VERSION TO v6.0 - UPDATED SECOND RULE SET");
279         SupportUtil.updateContainer("v6.0", specs);
280
281         kieSession.fireAllRules();
282         facts = getSessionObjects();
283
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( ")));
287     }
288
289     /**
290      * Updates the policy, changing the YAML associated with the first rule set.
291      *
292      * @param yamlFile name of the YAML file
293      * @param policyVersion policy version
294      * @throws IOException if an error occurs
295      */
296     private static void updatePolicy(String yamlFile, String policyVersion) throws IOException {
297
298         specifications[0] = new SupportUtil.RuleSpec(DROOLS_TEMPLATE, CONTROL_LOOP_NAME, POLICY_SCOPE, POLICY_NAME,
299                         policyVersion, loadYaml(yamlFile));
300
301         /*
302          * Update the policy within the container.
303          */
304         SupportUtil.updateContainer(policyVersion, specifications);
305     }
306
307     /**
308      * Loads a YAML file and URL-encodes it.
309      *
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
313      */
314     private static String loadYaml(String yamlFile) throws UnsupportedEncodingException {
315         Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml(yamlFile);
316         assertNotNull(pair);
317         assertNotNull(pair.first);
318         assertNotNull(pair.first.getControlLoop());
319         assertNotNull(pair.first.getControlLoop().getControlLoopName());
320         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
321
322         return URLEncoder.encode(pair.second, "UTF-8");
323     }
324
325     /**
326      * Gets the session objects.
327      *
328      * @return the session objects
329      */
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()));
334
335         lst.forEach(obj -> logger.info("obj={}", obj));
336
337         return lst;
338     }
339
340     /**
341      * Injects an ONSET event into the rule engine.
342      *
343      * @param controlLoopName the control loop name
344      */
345     private void injectEvent(String controlLoopName) {
346         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
347
348         event.setClosedLoopControlName(controlLoopName);
349
350         UUID reqid = UUID.randomUUID();
351         event.setRequestId(reqid);
352
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);
359
360         kieSession.insert(event);
361     }
362
363     /**
364      * Determines if the facts contain an event for the given control loop.
365      * 
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
370      */
371     private boolean hasEvent(List<Object> facts, String controlLoopName) {
372         return (facts.stream().anyMatch(obj -> obj instanceof VirtualControlLoopEvent
373                         && controlLoopName.equals(((VirtualControlLoopEvent) obj).getClosedLoopControlName())));
374     }
375 }