7549c6be65affd3c6e6d2a479b8495e63a4c2140
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 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.controlloop.common.rules.test;
22
23 import static org.awaitility.Awaitility.await;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertTrue;
27
28 import java.io.File;
29 import java.io.FileNotFoundException;
30 import java.io.IOException;
31 import java.util.Collections;
32 import java.util.List;
33 import java.util.Properties;
34 import java.util.concurrent.CountDownLatch;
35 import java.util.concurrent.TimeUnit;
36 import lombok.Getter;
37 import org.apache.commons.lang3.StringUtils;
38 import org.kie.api.event.rule.AfterMatchFiredEvent;
39 import org.kie.api.event.rule.BeforeMatchFiredEvent;
40 import org.kie.api.event.rule.DefaultAgendaEventListener;
41 import org.kie.api.event.rule.DefaultRuleRuntimeEventListener;
42 import org.kie.api.event.rule.MatchCancelledEvent;
43 import org.kie.api.event.rule.MatchCreatedEvent;
44 import org.kie.api.event.rule.ObjectDeletedEvent;
45 import org.kie.api.event.rule.ObjectInsertedEvent;
46 import org.kie.api.event.rule.ObjectUpdatedEvent;
47 import org.kie.api.event.rule.RuleRuntimeEventListener;
48 import org.kie.api.runtime.KieSession;
49 import org.onap.policy.common.utils.coder.CoderException;
50 import org.onap.policy.common.utils.coder.StandardCoder;
51 import org.onap.policy.common.utils.resources.ResourceUtils;
52 import org.onap.policy.controlloop.ControlLoopEvent;
53 import org.onap.policy.controlloop.drl.legacy.ControlLoopParams;
54 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager;
55 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager2;
56 import org.onap.policy.drools.controller.DroolsController;
57 import org.onap.policy.drools.persistence.SystemPersistence;
58 import org.onap.policy.drools.persistence.SystemPersistenceConstants;
59 import org.onap.policy.drools.system.PolicyController;
60 import org.onap.policy.drools.system.PolicyControllerConstants;
61 import org.onap.policy.drools.system.PolicyControllerFactory;
62 import org.onap.policy.drools.system.PolicyEngine;
63 import org.onap.policy.drools.system.PolicyEngineConstants;
64 import org.onap.policy.drools.util.KieUtils;
65 import org.onap.policy.drools.utils.logging.LoggerUtil;
66 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
67 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 /**
72  * Mechanism by which junit tests can manage the rule engine.
73  */
74 public class Rules {
75     private static final Logger logger = LoggerFactory.getLogger(Rules.class);
76     private static final StandardCoder coder = new StandardCoder();
77
78     /**
79      * PDP-D Engine.
80      */
81     @Getter
82     private final PolicyEngine pdpd = makeEngine();
83
84     /**
85      * PDP-D Configuration Repository.
86      */
87     @Getter
88     private final SystemPersistence pdpdRepo = makePdpdRepo();
89
90
91     @Getter
92     private final String controllerName;
93
94     @Getter
95     private PolicyController controller;
96
97
98     /**
99      * Constructs the object.
100      *
101      * @param controllerName name of the controller
102      */
103     public Rules(String controllerName) {
104         this.controllerName = controllerName;
105     }
106
107     /**
108      * Configures various items, including the PDP-D Engine.
109      *
110      * @param resourceDir path to resource directory
111      */
112     public void configure(String resourceDir) {
113         pdpdRepo.setConfigurationDir("src/test/resources/config");
114
115         try {
116             File kmoduleFile = new File(resourceDir + "/META-INF/kmodule.xml");
117             File pomFile = new File("src/test/resources/" + controllerName + ".pom");
118             String resourceDir2 = resourceDir + "/org/onap/policy/controlloop/";
119             File ruleFile = new File(resourceDir + "/" + controllerName + ".drl");
120             List<File> ruleFiles = Collections.singletonList(ruleFile);
121
122             installArtifact(kmoduleFile, pomFile, resourceDir2, ruleFiles);
123         } catch (IOException e) {
124             throw new IllegalArgumentException("cannot configure KIE session for " + controllerName, e);
125         }
126
127         setupLogging();
128
129         pdpd.configure(new Properties());
130     }
131
132     /**
133      * Starts various items, including the PDP-D Engine.
134      */
135     public void start() {
136         controller = pdpd.createPolicyController(controllerName, pdpdRepo.getControllerProperties(controllerName));
137         pdpd.start();
138
139         setupDroolsLogging();
140     }
141
142     /**
143      * Stop PDP-D.
144      */
145     public void destroy() {
146         getControllerFactory().shutdown(controllerName);
147         pdpd.stop();
148     }
149
150     /**
151      * Removes various facts from working memory, including the Policy and Params, as well
152      * as any event managers and events.
153      */
154     public void resetFacts() {
155         List<Class<?>> classes = List.of(ToscaPolicy.class, ControlLoopParams.class, ControlLoopEventManager2.class,
156                         ControlLoopEvent.class);
157
158         // delete all objects of the listed classes
159         DroolsController drools = controller.getDrools();
160         classes.forEach(drools::delete);
161
162         // wait for them to be deleted
163         for (Class<?> clazz : classes) {
164             await(clazz.getSimpleName()).atMost(5, TimeUnit.SECONDS)
165                             .until(() -> drools.facts(controllerName, clazz).isEmpty());
166         }
167
168         /*
169          * We can't delete this class directly; we have to wait for the rules to clean it
170          * up, because the rule also cleans up a number of other associated objects.
171          */
172         Class<?> clazz = ControlLoopEventManager.class;
173         await(clazz.getSimpleName()).atMost(5, TimeUnit.SECONDS)
174                         .until(() -> drools.facts(controllerName, clazz).isEmpty());
175     }
176
177     /**
178      * Installs a policy from policy/models (examples) repo.
179      */
180     public ToscaPolicy setupPolicyFromTemplate(String templatePath, String policyName) {
181         try {
182             return setupPolicy(getPolicyFromTemplate(templatePath, policyName));
183
184         } catch (InterruptedException | CoderException e) {
185             throw new IllegalArgumentException("policy " + policyName, e);
186         }
187     }
188
189     private ToscaPolicy getPolicyFromTemplate(String resourcePath, String policyName) throws CoderException {
190         String policyJson = ResourceUtils.getResourceAsString(resourcePath);
191         if (policyJson == null) {
192             throw new CoderException(new FileNotFoundException(resourcePath));
193         }
194
195         ToscaServiceTemplate serviceTemplate = coder.decode(policyJson, ToscaServiceTemplate.class);
196         ToscaPolicy policy = serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyName);
197         assertNotNull(policy);
198
199         /*
200          * name and version are used within a drl. api component and drools core will
201          * ensure that these are populated.
202          */
203         if (StringUtils.isBlank(policy.getName())) {
204             policy.setName(policyName);
205         }
206
207         if (StringUtils.isBlank(policy.getVersion())) {
208             policy.setVersion(policy.getTypeVersion());
209         }
210
211         return serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyName);
212     }
213
214     /**
215      * Installs a given policy.
216      */
217     public ToscaPolicy setupPolicyFromFile(String policyPath) {
218         try {
219             return setupPolicy(getPolicyFromFile(policyPath));
220
221         } catch (InterruptedException | IOException | CoderException e) {
222             throw new IllegalArgumentException("policy " + policyPath, e);
223         }
224     }
225
226     private ToscaPolicy getPolicyFromFile(String policyPath) throws IOException, CoderException {
227         String policyJson = ResourceUtils.getResourceAsString(policyPath);
228         if (policyJson == null) {
229             throw new CoderException(new FileNotFoundException(policyPath));
230         }
231
232         return coder.decode(policyJson, ToscaPolicy.class);
233     }
234
235     private ToscaPolicy setupPolicy(ToscaPolicy policy) throws InterruptedException {
236         final KieObjectExpectedCallback<?> policyTracker = new KieObjectInsertedExpectedCallback<>(policy);
237         final KieObjectExpectedCallback<?> paramsTracker =
238                         new KieClassInsertedExpectedCallback<>(ControlLoopParams.class);
239
240         controller.getDrools().offer(policy);
241
242         assertTrue(policyTracker.isNotified());
243         assertTrue(paramsTracker.isNotified());
244
245         assertEquals(1, controller.getDrools().facts(controllerName, ToscaPolicy.class).stream()
246                         .filter((anotherPolicy) -> anotherPolicy == policy).count());
247
248         assertEquals(1, controller.getDrools().facts(controllerName, ControlLoopParams.class).stream()
249                         .filter((params) -> params.getToscaPolicy() == policy).count());
250         return policy;
251     }
252
253     /**
254      * Sets up overall logging.
255      */
256     private void setupLogging() {
257         LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "WARN");
258         LoggerUtil.setLevel("org.eclipse.jetty", "WARN");
259         LoggerUtil.setLevel("org.onap.policy.controlloop", "INFO");
260         LoggerUtil.setLevel("network", "INFO");
261     }
262
263     /**
264      * Sets up Drools Logging for events of interest.
265      */
266     private void setupDroolsLogging() {
267         KieSession session = getKieSession();
268
269         session.addEventListener(new RuleListenerLogger());
270         session.addEventListener(new AgendaListenerLogger());
271     }
272
273     /**
274      * Logs Modifications to Working Memory.
275      */
276     private static class RuleListenerLogger implements RuleRuntimeEventListener {
277         @Override
278         public void objectInserted(ObjectInsertedEvent event) {
279             String ruleName = (event.getRule() != null) ? event.getRule().getName() : "null";
280             logger.info("RULE {}: inserted {}", ruleName, event.getObject());
281         }
282
283         @Override
284         public void objectUpdated(ObjectUpdatedEvent event) {
285             String ruleName = (event.getRule() != null) ? event.getRule().getName() : "null";
286             logger.info("RULE {}: updated {}", ruleName, event.getObject());
287
288         }
289
290         @Override
291         public void objectDeleted(ObjectDeletedEvent event) {
292             String ruleName = (event.getRule() != null) ? event.getRule().getName() : "null";
293             logger.info("RULE {}: deleted {}", ruleName, event.getOldObject());
294         }
295     }
296
297     /**
298      * Logs Rule Matches.
299      */
300     private static class AgendaListenerLogger extends DefaultAgendaEventListener {
301         @Override
302         public void matchCreated(MatchCreatedEvent event) {
303             logger.info("RULE {}: match created", event.getMatch().getRule().getName());
304         }
305
306         @Override
307         public void matchCancelled(MatchCancelledEvent event) {
308             logger.info("RULE {}: match cancelled", event.getMatch().getRule().getName());
309         }
310
311         @Override
312         public void beforeMatchFired(BeforeMatchFiredEvent event) {
313             logger.info("RULE {}: before match fired", event.getMatch().getRule().getName());
314         }
315
316         @Override
317         public void afterMatchFired(AfterMatchFiredEvent event) {
318             logger.info("RULE {}: after match fired", event.getMatch().getRule().getName());
319         }
320     }
321
322     /**
323      * Base Class to track Working Memory updates for objects of type T.
324      */
325     private abstract class KieObjectExpectedCallback<T> extends DefaultRuleRuntimeEventListener {
326         protected T subject;
327
328         protected CountDownLatch countDownLatch = new CountDownLatch(1);
329
330         public KieObjectExpectedCallback(T affected) {
331             subject = affected;
332             register();
333         }
334
335         public boolean isNotified() throws InterruptedException {
336             return countDownLatch.await(9L, TimeUnit.SECONDS);
337         }
338
339         protected void callbacked() {
340             unregister();
341             countDownLatch.countDown();
342         }
343
344         public KieObjectExpectedCallback<T> register() {
345             getKieSession().addEventListener(this);
346             return this;
347         }
348
349         public KieObjectExpectedCallback<T> unregister() {
350             getKieSession().removeEventListener(this);
351             return this;
352         }
353     }
354
355     /**
356      * Tracks inserts in Working Memory for an object of type T.
357      */
358     private class KieObjectInsertedExpectedCallback<T> extends KieObjectExpectedCallback<T> {
359         public KieObjectInsertedExpectedCallback(T affected) {
360             super(affected);
361         }
362
363         @Override
364         public void objectInserted(ObjectInsertedEvent event) {
365             if (subject == event.getObject()) {
366                 callbacked();
367             }
368         }
369     }
370
371     /**
372      * Tracks inserts in Working Memory for any object of class T.
373      */
374     private class KieClassInsertedExpectedCallback<T> extends KieObjectInsertedExpectedCallback<T> {
375
376         public KieClassInsertedExpectedCallback(T affected) {
377             super(affected);
378         }
379
380         public void objectInserted(ObjectInsertedEvent event) {
381             if (subject == event.getObject().getClass()) {
382                 callbacked();
383             }
384         }
385     }
386
387     // these may be overridden by junit tests
388
389
390     protected PolicyEngine makeEngine() {
391         return PolicyEngineConstants.getManager();
392     }
393
394
395     protected SystemPersistence makePdpdRepo() {
396         return SystemPersistenceConstants.getManager();
397     }
398
399     protected KieSession getKieSession() {
400         return getControllerFactory().get(controllerName).getDrools().getContainer().getPolicySession(controllerName)
401                         .getKieSession();
402     }
403
404     protected PolicyControllerFactory getControllerFactory() {
405         return PolicyControllerConstants.getFactory();
406     }
407
408     protected void installArtifact(File kmoduleFile, File pomFile, String resourceDir, List<File> ruleFiles)
409                     throws IOException {
410
411         KieUtils.installArtifact(kmoduleFile, pomFile, resourceDir, ruleFiles);
412     }
413 }