9b832b0421d10071bc22db96d12027d42dcbfa6d
[policy/drools-pdp.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2017-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.drools.controller.internal;
22
23 import com.fasterxml.jackson.annotation.JsonIgnore;
24 import com.fasterxml.jackson.annotation.JsonProperty;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Objects;
31 import java.util.stream.Collectors;
32 import org.apache.commons.collections4.queue.CircularFifoQueue;
33 import org.checkerframework.checker.nullness.qual.NonNull;
34 import org.drools.core.ClassObjectFilter;
35 import org.kie.api.definition.KiePackage;
36 import org.kie.api.definition.rule.Query;
37 import org.kie.api.runtime.KieSession;
38 import org.kie.api.runtime.rule.FactHandle;
39 import org.kie.api.runtime.rule.QueryResults;
40 import org.kie.api.runtime.rule.QueryResultsRow;
41 import org.onap.policy.common.endpoints.event.comm.TopicSink;
42 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
43 import org.onap.policy.common.gson.annotation.GsonJsonProperty;
44 import org.onap.policy.common.utils.services.FeatureApiUtils;
45 import org.onap.policy.common.utils.services.OrderedServiceImpl;
46 import org.onap.policy.drools.controller.DroolsController;
47 import org.onap.policy.drools.controller.DroolsControllerConstants;
48 import org.onap.policy.drools.core.PolicyContainer;
49 import org.onap.policy.drools.core.PolicySession;
50 import org.onap.policy.drools.core.jmx.PdpJmx;
51 import org.onap.policy.drools.features.DroolsControllerFeatureApi;
52 import org.onap.policy.drools.features.DroolsControllerFeatureApiConstants;
53 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
54 import org.onap.policy.drools.protocol.coders.EventProtocolCoderConstants;
55 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
56 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
57 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration;
58 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomGsonCoder;
59 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.PotentialCoderFilter;
60 import org.onap.policy.drools.utils.ReflectionUtil;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 /**
65  * Maven-based Drools Controller that interacts with the
66  * policy-core PolicyContainer and PolicySession to manage
67  * Drools containers instantiated using Maven.
68  */
69 public class MavenDroolsController implements DroolsController {
70
71     private static final String FACT_RETRIEVE_ERROR = "Object cannot be retrieved from fact {}";
72
73     /**
74      * logger.
75      */
76     private static Logger  logger = LoggerFactory.getLogger(MavenDroolsController.class);
77
78     /**
79      * Policy Container, the access object to the policy-core layer.
80      */
81     @JsonIgnore
82     @GsonJsonIgnore
83     protected final PolicyContainer policyContainer;
84
85     /**
86      * alive status of this drools controller,
87      * reflects invocation of start()/stop() only.
88      */
89     protected volatile boolean alive = false;
90
91     /**
92      * locked status of this drools controller,
93      * reflects if i/o drools related operations are permitted,
94      * more specifically: offer() and deliver().
95      * It does not affect the ability to start and stop
96      * underlying drools infrastructure
97      */
98     protected volatile boolean locked = false;
99
100     /**
101      * list of topics, each with associated decoder classes, each
102      * with a list of associated filters.
103      */
104     protected List<TopicCoderFilterConfiguration> decoderConfigurations;
105
106     /**
107      * list of topics, each with associated encoder classes, each
108      * with a list of associated filters.
109      */
110     protected List<TopicCoderFilterConfiguration> encoderConfigurations;
111
112     /**
113      * recent source events processed.
114      */
115     protected final CircularFifoQueue<Object> recentSourceEvents = new CircularFifoQueue<>(10);
116
117     /**
118      * recent sink events processed.
119      */
120     protected final CircularFifoQueue<String> recentSinkEvents = new CircularFifoQueue<>(10);
121
122     /**
123      * original Drools Model/Rules classloader hash.
124      */
125     protected int modelClassLoaderHash;
126
127     /**
128      * Expanded version of the constructor.
129      *
130      * @param groupId maven group id
131      * @param artifactId maven artifact id
132      * @param version maven version
133      * @param decoderConfigurations list of topic -> decoders -> filters mapping
134      * @param encoderConfigurations list of topic -> encoders -> filters mapping
135      *
136      * @throws IllegalArgumentException invalid arguments passed in
137      */
138     public MavenDroolsController(String groupId,
139             String artifactId,
140             String version,
141             List<TopicCoderFilterConfiguration> decoderConfigurations,
142             List<TopicCoderFilterConfiguration> encoderConfigurations) {
143
144         logger.info("drools-controller instantiation [{}:{}:{}]", groupId, artifactId, version);
145
146         if (groupId == null || groupId.isEmpty()) {
147             throw new IllegalArgumentException("Missing maven group-id coordinate");
148         }
149
150         if (artifactId == null || artifactId.isEmpty()) {
151             throw new IllegalArgumentException("Missing maven artifact-id coordinate");
152         }
153
154         if (version == null || version.isEmpty()) {
155             throw new IllegalArgumentException("Missing maven version coordinate");
156         }
157
158         this.policyContainer = makePolicyContainer(groupId, artifactId, version);
159         this.init(decoderConfigurations, encoderConfigurations);
160
161         logger.debug("{}: instantiation completed ", this);
162     }
163
164     /**
165      * init encoding/decoding configuration.
166      *
167      * @param decoderConfigurations list of topic -> decoders -> filters mapping
168      * @param encoderConfigurations list of topic -> encoders -> filters mapping
169      */
170     protected void init(List<TopicCoderFilterConfiguration> decoderConfigurations,
171             List<TopicCoderFilterConfiguration> encoderConfigurations) {
172
173         this.decoderConfigurations = decoderConfigurations;
174         this.encoderConfigurations = encoderConfigurations;
175
176         this.initCoders(decoderConfigurations, true);
177         this.initCoders(encoderConfigurations, false);
178
179         this.modelClassLoaderHash = this.policyContainer.getClassLoader().hashCode();
180     }
181
182     @Override
183     public void updateToVersion(String newGroupId, String newArtifactId, String newVersion,
184             List<TopicCoderFilterConfiguration> decoderConfigurations,
185             List<TopicCoderFilterConfiguration> encoderConfigurations)
186                     throws LinkageError {
187
188         logger.info("updating version -> [{}:{}:{}]", newGroupId, newArtifactId, newVersion);
189
190         validateText(newGroupId, "Missing maven group-id coordinate");
191         validateText(newArtifactId, "Missing maven artifact-id coordinate");
192         validateText(newVersion, "Missing maven version coordinate");
193
194         validateHasBrain(newGroupId, newArtifactId, newVersion);
195
196         if (newGroupId.equalsIgnoreCase(this.getGroupId())
197                 && newArtifactId.equalsIgnoreCase(this.getArtifactId())
198                 && newVersion.equalsIgnoreCase(this.getVersion())) {
199             logger.warn("All in the right version: " + newGroupId + ":"
200                     + newArtifactId + ":" +  newVersion + " vs. " + this);
201             return;
202         }
203
204         validateNewVersion(newGroupId, newArtifactId, newVersion);
205
206         /* upgrade */
207         String messages = this.policyContainer.updateToVersion(newVersion);
208         logger.warn("{} UPGRADE results: {}", this, messages);
209
210         /*
211          * If all sucessful (can load new container), now we can remove all coders from previous sessions
212          */
213         this.removeCoders();
214
215         /*
216          * add the new coders
217          */
218         this.init(decoderConfigurations, encoderConfigurations);
219
220         logger.info("UPDATE-TO-VERSION: completed {}", this);
221     }
222
223     private void validateText(String text, String errorMessage) {
224         if (text == null || text.isEmpty()) {
225             throw new IllegalArgumentException(errorMessage);
226         }
227     }
228
229     private void validateHasBrain(String newGroupId, String newArtifactId, String newVersion) {
230         if (newGroupId.equalsIgnoreCase(DroolsControllerConstants.NO_GROUP_ID)
231                 || newArtifactId.equalsIgnoreCase(DroolsControllerConstants.NO_ARTIFACT_ID)
232                 || newVersion.equalsIgnoreCase(DroolsControllerConstants.NO_VERSION)) {
233             throw new IllegalArgumentException("BRAINLESS maven coordinates provided: "
234                     + newGroupId + ":" + newArtifactId + ":"
235                     + newVersion);
236         }
237     }
238
239     private void validateNewVersion(String newGroupId, String newArtifactId, String newVersion) {
240         if (!newGroupId.equalsIgnoreCase(this.getGroupId())
241                 || !newArtifactId.equalsIgnoreCase(this.getArtifactId())) {
242             throw new IllegalArgumentException(
243                     "Group ID and Artifact ID maven coordinates must be identical for the upgrade: "
244                     + newGroupId + ":" + newArtifactId + ":"
245                     + newVersion + " vs. " + this);
246         }
247     }
248
249     /**
250      * initialize decoders for all the topics supported by this controller
251      * Note this is critical to be done after the Policy Container is
252      * instantiated to be able to fetch the corresponding classes.
253      *
254      * @param coderConfigurations list of topic -> decoders -> filters mapping
255      */
256     protected void initCoders(List<TopicCoderFilterConfiguration> coderConfigurations,
257             boolean decoder) {
258
259         logger.info("INIT-CODERS: {}", this);
260
261         if (coderConfigurations == null) {
262             return;
263         }
264
265
266         for (TopicCoderFilterConfiguration coderConfig: coderConfigurations) {
267             String topic = coderConfig.getTopic();
268
269             CustomGsonCoder customGsonCoder = getCustomCoder(coderConfig);
270
271             List<PotentialCoderFilter> coderFilters = coderConfig.getCoderFilters();
272             if (coderFilters == null || coderFilters.isEmpty()) {
273                 continue;
274             }
275
276             for (PotentialCoderFilter coderFilter : coderFilters) {
277                 String potentialCodedClass = coderFilter.getCodedClass();
278                 JsonProtocolFilter protocolFilter = coderFilter.getFilter();
279
280                 if (!isClass(potentialCodedClass)) {
281                     throw makeRetrieveEx(potentialCodedClass);
282                 } else {
283                     logClassFetched(potentialCodedClass);
284                 }
285
286                 if (decoder) {
287                     getCoderManager().addDecoder(EventProtocolParams.builder()
288                             .groupId(this.getGroupId())
289                             .artifactId(this.getArtifactId())
290                             .topic(topic)
291                             .eventClass(potentialCodedClass)
292                             .protocolFilter(protocolFilter)
293                             .customGsonCoder(customGsonCoder)
294                             .modelClassLoaderHash(this.policyContainer.getClassLoader().hashCode()));
295                 } else {
296                     getCoderManager().addEncoder(
297                             EventProtocolParams.builder().groupId(this.getGroupId())
298                                     .artifactId(this.getArtifactId()).topic(topic)
299                                     .eventClass(potentialCodedClass).protocolFilter(protocolFilter)
300                                     .customGsonCoder(customGsonCoder)
301                                     .modelClassLoaderHash(this.policyContainer.getClassLoader().hashCode()));
302                 }
303             }
304         }
305     }
306
307     private CustomGsonCoder getCustomCoder(TopicCoderFilterConfiguration coderConfig) {
308         CustomGsonCoder customGsonCoder = coderConfig.getCustomGsonCoder();
309         if (customGsonCoder != null
310                 && customGsonCoder.getClassContainer() != null
311                 && !customGsonCoder.getClassContainer().isEmpty()) {
312
313             String customGsonCoderClass = customGsonCoder.getClassContainer();
314             if (!isClass(customGsonCoderClass)) {
315                 throw makeRetrieveEx(customGsonCoderClass);
316             } else {
317                 logClassFetched(customGsonCoderClass);
318             }
319         }
320         return customGsonCoder;
321     }
322
323     /**
324      * Logs an error and makes an exception for an item that cannot be retrieved.
325      * @param itemName the item to retrieve
326      * @return a new exception
327      */
328     private IllegalArgumentException makeRetrieveEx(String itemName) {
329         logger.error("{} cannot be retrieved", itemName);
330         return new IllegalArgumentException(itemName + " cannot be retrieved");
331     }
332
333     /**
334      * Logs the name of the class that was fetched.
335      * @param className class name fetched
336      */
337     private void logClassFetched(String className) {
338         logger.info("CLASS FETCHED {}", className);
339     }
340
341
342     /**
343      * remove decoders.
344      */
345     protected void removeDecoders() {
346         logger.info("REMOVE-DECODERS: {}", this);
347
348         if (this.decoderConfigurations == null) {
349             return;
350         }
351
352
353         for (TopicCoderFilterConfiguration coderConfig: decoderConfigurations) {
354             String topic = coderConfig.getTopic();
355             getCoderManager().removeDecoders(this.getGroupId(), this.getArtifactId(), topic);
356         }
357     }
358
359     /**
360      * remove decoders.
361      */
362     protected void removeEncoders() {
363
364         logger.info("REMOVE-ENCODERS: {}", this);
365
366         if (this.encoderConfigurations == null) {
367             return;
368         }
369
370         for (TopicCoderFilterConfiguration coderConfig: encoderConfigurations) {
371             String topic = coderConfig.getTopic();
372             getCoderManager().removeEncoders(this.getGroupId(), this.getArtifactId(), topic);
373         }
374     }
375
376
377     @Override
378     public boolean ownsCoder(Class<?> coderClass, int modelHash) {
379         if (!isClass(coderClass.getName())) {
380             logger.error("{}{} cannot be retrieved. ", this, coderClass.getName());
381             return false;
382         }
383
384         if (modelHash == this.modelClassLoaderHash) {
385             logger.info("{}{} class loader matches original drools controller rules classloader {}",
386                             coderClass.getName(), this, coderClass.getClassLoader());
387             return true;
388         } else {
389             logger.warn("{}{} class loaders don't match {} vs {}", this, coderClass.getName(),
390                             coderClass.getClassLoader(), this.policyContainer.getClassLoader());
391             return false;
392         }
393     }
394
395     @Override
396     public boolean start() {
397
398         logger.info("START: {}", this);
399
400         synchronized (this) {
401             if (this.alive) {
402                 return true;
403             }
404             this.alive = true;
405         }
406
407         return this.policyContainer.start();
408     }
409
410     @Override
411     public boolean stop() {
412
413         logger.info("STOP: {}", this);
414
415         synchronized (this) {
416             if (!this.alive) {
417                 return true;
418             }
419             this.alive = false;
420         }
421
422         return this.policyContainer.stop();
423     }
424
425     @Override
426     public void shutdown() {
427         logger.info("{}: SHUTDOWN", this);
428
429         try {
430             this.stop();
431             this.removeCoders();
432         } catch (Exception e) {
433             logger.error("{} SHUTDOWN FAILED because of {}", this, e.getMessage(), e);
434         } finally {
435             this.policyContainer.shutdown();
436         }
437
438     }
439
440     @Override
441     public void halt() {
442         logger.info("{}: HALT", this);
443
444         try {
445             this.stop();
446             this.removeCoders();
447         } catch (Exception e) {
448             logger.error("{} HALT FAILED because of {}", this, e.getMessage(), e);
449         } finally {
450             this.policyContainer.destroy();
451         }
452     }
453
454     /**
455      * removes this drools controllers and encoders and decoders from operation.
456      */
457     protected void removeCoders() {
458         logger.info("{}: REMOVE-CODERS", this);
459
460         try {
461             this.removeDecoders();
462         } catch (IllegalArgumentException e) {
463             logger.error("{} REMOVE-DECODERS FAILED because of {}", this, e.getMessage(), e);
464         }
465
466         try {
467             this.removeEncoders();
468         } catch (IllegalArgumentException e) {
469             logger.error("{} REMOVE-ENCODERS FAILED because of {}", this, e.getMessage(), e);
470         }
471     }
472
473     @Override
474     public boolean isAlive() {
475         return this.alive;
476     }
477
478     @Override
479     public boolean offer(String topic, String event) {
480         logger.debug("{}: OFFER raw event from {}", this, topic);
481
482         if (this.locked || !this.alive || this.policyContainer.getPolicySessions().isEmpty()) {
483             return true;
484         }
485
486         // 1. Now, check if this topic has a decoder:
487
488         if (!getCoderManager().isDecodingSupported(this.getGroupId(),
489                 this.getArtifactId(),
490                 topic)) {
491
492             logger.warn("{}: DECODING-UNSUPPORTED {}:{}:{}", this,
493                     topic, this.getGroupId(), this.getArtifactId());
494             return true;
495         }
496
497         // 2. Decode
498
499         Object anEvent;
500         try {
501             anEvent = getCoderManager().decode(this.getGroupId(),
502                     this.getArtifactId(),
503                     topic,
504                     event);
505         } catch (UnsupportedOperationException uoe) {
506             logger.debug("{}: DECODE FAILED: {} <- {} because of {}", this, topic,
507                     event, uoe.getMessage(), uoe);
508             return true;
509         } catch (Exception e) {
510             logger.warn("{}: DECODE FAILED: {} <- {} because of {}", this, topic,
511                     event, e.getMessage(), e);
512             return true;
513         }
514
515         return offer(anEvent);
516
517     }
518
519     @Override
520     public <T> boolean offer(T event) {
521         logger.debug("{}: OFFER event", this);
522
523         if (this.locked || !this.alive || this.policyContainer.getPolicySessions().isEmpty()) {
524             return true;
525         }
526
527         synchronized (this.recentSourceEvents) {
528             this.recentSourceEvents.add(event);
529         }
530
531         PdpJmx.getInstance().updateOccured();
532
533         // Broadcast
534
535         if (FeatureApiUtils.apply(getDroolsProviders().getList(),
536             feature -> feature.beforeInsert(this, event),
537             (feature, ex) -> logger.error("{}: feature {} before-insert failure because of {}", this,
538                             feature.getClass().getName(), ex.getMessage(), ex))) {
539             return true;
540         }
541
542         boolean successInject = this.policyContainer.insertAll(event);
543         if (!successInject) {
544             logger.warn(this + "Failed to inject into PolicyContainer {}", this.getSessionNames());
545         }
546
547         FeatureApiUtils.apply(getDroolsProviders().getList(),
548             feature -> feature.afterInsert(this, event, successInject),
549             (feature, ex) -> logger.error("{}: feature {} after-insert failure because of {}", this,
550                             feature.getClass().getName(), ex.getMessage(), ex));
551
552         return true;
553
554     }
555
556     @Override
557     public boolean deliver(TopicSink sink, Object event) {
558
559         logger.info("{}DELIVER: {} FROM {} TO {}", this, event, this, sink);
560
561         for (DroolsControllerFeatureApi feature : getDroolsProviders().getList()) {
562             try {
563                 if (feature.beforeDeliver(this, sink, event)) {
564                     return true;
565                 }
566             }
567             catch (Exception e) {
568                 logger.error("{}: feature {} before-deliver failure because of {}", this, feature.getClass().getName(),
569                         e.getMessage(), e);
570             }
571         }
572
573         if (sink == null) {
574             throw new IllegalArgumentException(this +  " invalid sink");
575         }
576
577         if (event == null) {
578             throw new IllegalArgumentException(this +  " invalid event");
579         }
580
581         if (this.locked) {
582             throw new IllegalStateException(this +  " is locked");
583         }
584
585         if (!this.alive) {
586             throw new IllegalStateException(this +  " is stopped");
587         }
588
589         String json =
590                 getCoderManager().encode(sink.getTopic(), event, this);
591
592         synchronized (this.recentSinkEvents) {
593             this.recentSinkEvents.add(json);
594         }
595
596         boolean success = sink.send(json);
597
598         for (DroolsControllerFeatureApi feature : getDroolsProviders().getList()) {
599             try {
600                 if (feature.afterDeliver(this, sink, event, json, success)) {
601                     return true;
602                 }
603             }
604             catch (Exception e) {
605                 logger.error("{}: feature {} after-deliver failure because of {}", this, feature.getClass().getName(),
606                         e.getMessage(), e);
607             }
608         }
609
610         return success;
611
612     }
613
614     @Override
615     public String getVersion() {
616         return this.policyContainer.getVersion();
617     }
618
619     @Override
620     public String getArtifactId() {
621         return this.policyContainer.getArtifactId();
622     }
623
624     @Override
625     public String getGroupId() {
626         return this.policyContainer.getGroupId();
627     }
628
629     /**
630      * Get model class loader hash.
631      *
632      * @return the modelClassLoaderHash
633      */
634     public int getModelClassLoaderHash() {
635         return modelClassLoaderHash;
636     }
637
638     @Override
639     public synchronized boolean lock() {
640         logger.info("LOCK: {}",  this);
641
642         this.locked = true;
643         return true;
644     }
645
646     @Override
647     public synchronized boolean unlock() {
648         logger.info("UNLOCK: {}",  this);
649
650         this.locked = false;
651         return true;
652     }
653
654     @Override
655     public boolean isLocked() {
656         return this.locked;
657     }
658
659     @JsonIgnore
660     @GsonJsonIgnore
661     @Override
662     public PolicyContainer getContainer() {
663         return this.policyContainer;
664     }
665
666     @JsonProperty("sessions")
667     @GsonJsonProperty("sessions")
668     @Override
669     public List<String> getSessionNames() {
670         return getSessionNames(true);
671     }
672
673     /**
674      * get session names.
675      *
676      * @param abbreviated true for the short form, otherwise the long form
677      * @return session names
678      */
679     protected List<String> getSessionNames(boolean abbreviated) {
680         List<String> sessionNames = new ArrayList<>();
681         try {
682             for (PolicySession session: this.policyContainer.getPolicySessions()) {
683                 if (abbreviated) {
684                     sessionNames.add(session.getName());
685                 } else {
686                     sessionNames.add(session.getFullName());
687                 }
688             }
689         } catch (Exception e) {
690             logger.warn("Can't retrieve CORE sessions: " + e.getMessage(), e);
691             sessionNames.add(e.getMessage());
692         }
693         return sessionNames;
694     }
695
696     @JsonProperty("sessionCoordinates")
697     @GsonJsonProperty("sessionCoordinates")
698     @Override
699     public List<String> getCanonicalSessionNames() {
700         return getSessionNames(false);
701     }
702
703     @Override
704     public List<String> getBaseDomainNames() {
705         return new ArrayList<>(this.policyContainer.getKieContainer().getKieBaseNames());
706     }
707
708     /**
709      * provides the underlying core layer container sessions.
710      *
711      * @return the attached Policy Container
712      */
713     protected List<PolicySession> getSessions() {
714         List<PolicySession> sessions = new ArrayList<>();
715         sessions.addAll(this.policyContainer.getPolicySessions());
716         return sessions;
717     }
718
719     /**
720      * provides the underlying core layer container session with name sessionName.
721      *
722      * @param sessionName session name
723      * @return the attached Policy Container
724      * @throws IllegalArgumentException when an invalid session name is provided
725      * @throws IllegalStateException when the drools controller is in an invalid state
726      */
727     protected PolicySession getSession(String sessionName) {
728         if (sessionName == null || sessionName.isEmpty()) {
729             throw new IllegalArgumentException("A Session Name must be provided");
730         }
731
732         List<PolicySession> sessions = this.getSessions();
733         for (PolicySession session : sessions) {
734             if (sessionName.equals(session.getName()) || sessionName.equals(session.getFullName())) {
735                 return session;
736             }
737         }
738
739         throw invalidSessNameEx(sessionName);
740     }
741
742     private IllegalArgumentException invalidSessNameEx(String sessionName) {
743         return new IllegalArgumentException("Invalid Session Name: " + sessionName);
744     }
745
746     @Override
747     public Map<String,Integer> factClassNames(String sessionName) {
748         validateSessionName(sessionName);
749
750         Map<String,Integer> classNames = new HashMap<>();
751
752         PolicySession session = getSession(sessionName);
753         KieSession kieSession = session.getKieSession();
754
755         Collection<FactHandle> facts = kieSession.getFactHandles();
756         for (FactHandle fact : facts) {
757             try {
758                 String className = kieSession.getObject(fact).getClass().getName();
759                 if (classNames.containsKey(className)) {
760                     classNames.put(className, classNames.get(className) + 1);
761                 } else {
762                     classNames.put(className, 1);
763                 }
764             } catch (Exception e) {
765                 logger.warn(FACT_RETRIEVE_ERROR, fact, e);
766             }
767         }
768
769         return classNames;
770     }
771
772     private void validateSessionName(String sessionName) {
773         if (sessionName == null || sessionName.isEmpty()) {
774             throw invalidSessNameEx(sessionName);
775         }
776     }
777
778     @Override
779     public long factCount(String sessionName) {
780         validateSessionName(sessionName);
781
782         PolicySession session = getSession(sessionName);
783         return session.getKieSession().getFactCount();
784     }
785
786     @Override
787     public List<Object> facts(String sessionName, String className, boolean delete) {
788         validateSessionName(sessionName);
789
790         if (className == null || className.isEmpty()) {
791             throw new IllegalArgumentException("Invalid Class Name: " + className);
792         }
793
794         Class<?> factClass =
795                 ReflectionUtil.fetchClass(this.policyContainer.getClassLoader(), className);
796         if (factClass == null) {
797             throw new IllegalArgumentException("Class cannot be fetched in model's classloader: " + className);
798         }
799
800         PolicySession session = getSession(sessionName);
801         KieSession kieSession = session.getKieSession();
802
803         List<Object> factObjects = new ArrayList<>();
804
805         Collection<FactHandle> factHandles = kieSession.getFactHandles(new ClassObjectFilter(factClass));
806         for (FactHandle factHandle : factHandles) {
807             try {
808                 factObjects.add(kieSession.getObject(factHandle));
809                 if (delete) {
810                     kieSession.delete(factHandle);
811                 }
812             } catch (Exception e) {
813                 logger.warn(FACT_RETRIEVE_ERROR, factHandle, e);
814             }
815         }
816
817         return factObjects;
818     }
819
820     @Override
821     public <T> List<T> facts(@NonNull String sessionName, @NonNull Class<T> clazz) {
822         return facts(sessionName, clazz.getName(), false)
823             .stream()
824             .filter(clazz::isInstance)
825             .map(clazz::cast)
826             .collect(Collectors.toList());
827     }
828
829     @Override
830     public List<Object> factQuery(String sessionName, String queryName, String queriedEntity,
831             boolean delete, Object... queryParams) {
832         validateSessionName(sessionName);
833
834         if (queryName == null || queryName.isEmpty()) {
835             throw new IllegalArgumentException("Invalid Query Name: " + queryName);
836         }
837
838         if (queriedEntity == null || queriedEntity.isEmpty()) {
839             throw new IllegalArgumentException("Invalid Queried Entity: " + queriedEntity);
840         }
841
842         PolicySession session = getSession(sessionName);
843         KieSession kieSession = session.getKieSession();
844
845         validateQueryName(kieSession, queryName);
846
847         List<Object> factObjects = new ArrayList<>();
848
849         QueryResults queryResults = kieSession.getQueryResults(queryName, queryParams);
850         for (QueryResultsRow row : queryResults) {
851             try {
852                 factObjects.add(row.get(queriedEntity));
853                 if (delete) {
854                     kieSession.delete(row.getFactHandle(queriedEntity));
855                 }
856             } catch (Exception e) {
857                 logger.warn("Object cannot be retrieved from row: {}", row, e);
858             }
859         }
860
861         return factObjects;
862     }
863
864     private void validateQueryName(KieSession kieSession, String queryName) {
865         for (KiePackage kiePackage : kieSession.getKieBase().getKiePackages()) {
866             for (Query q : kiePackage.getQueries()) {
867                 if (q.getName() != null && q.getName().equals(queryName)) {
868                     return;
869                 }
870             }
871         }
872
873         throw new IllegalArgumentException("Invalid Query Name: " + queryName);
874     }
875
876     @Override
877     public <T> boolean delete(@NonNull String sessionName, @NonNull T fact) {
878         String factClassName = fact.getClass().getName();
879
880         PolicySession session = getSession(sessionName);
881         KieSession kieSession = session.getKieSession();
882
883         Collection<FactHandle> factHandles = kieSession.getFactHandles(new ClassObjectFilter(fact.getClass()));
884         for (FactHandle factHandle : factHandles) {
885             try {
886                 if (Objects.equals(fact, kieSession.getObject(factHandle))) {
887                     logger.info("Deleting {} from {}", factClassName, sessionName);
888                     kieSession.delete(factHandle);
889                     return true;
890                 }
891             } catch (Exception e) {
892                 logger.warn(FACT_RETRIEVE_ERROR, factHandle, e);
893             }
894         }
895         return false;
896     }
897
898     @Override
899     public <T> boolean delete(@NonNull T fact) {
900         return this.getSessionNames().stream().map(ss -> delete(ss, fact)).reduce(false, Boolean::logicalOr);
901     }
902
903     @Override
904     public <T> boolean delete(@NonNull String sessionName, @NonNull Class<T> fact) {
905         PolicySession session = getSession(sessionName);
906         KieSession kieSession = session.getKieSession();
907
908         boolean success = true;
909         Collection<FactHandle> factHandles = kieSession.getFactHandles(new ClassObjectFilter(fact));
910         for (FactHandle factHandle : factHandles) {
911             try {
912                 kieSession.delete(factHandle);
913             } catch (Exception e) {
914                 logger.warn(FACT_RETRIEVE_ERROR, factHandle, e);
915                 success = false;
916             }
917         }
918         return success;
919     }
920
921     @Override
922     public <T> boolean delete(@NonNull Class<T> fact) {
923         return this.getSessionNames().stream().map(ss -> delete(ss, fact)).reduce(false, Boolean::logicalOr);
924     }
925
926
927     @Override
928     public Class<?> fetchModelClass(String className) {
929         return ReflectionUtil.fetchClass(this.policyContainer.getClassLoader(), className);
930     }
931
932     /**
933      * Get recent source events.
934      *
935      * @return the recentSourceEvents
936      */
937     @Override
938     public Object[] getRecentSourceEvents() {
939         synchronized (this.recentSourceEvents) {
940             Object[] events = new Object[recentSourceEvents.size()];
941             return recentSourceEvents.toArray(events);
942         }
943     }
944
945     /**
946      * Get recent sink events.
947      *
948      * @return the recentSinkEvents
949      */
950     @Override
951     public String[] getRecentSinkEvents() {
952         synchronized (this.recentSinkEvents) {
953             String[] events = new String[recentSinkEvents.size()];
954             return recentSinkEvents.toArray(events);
955         }
956     }
957
958     @Override
959     public boolean isBrained() {
960         return true;
961     }
962
963
964     @Override
965     public String toString() {
966         StringBuilder builder = new StringBuilder();
967         builder
968             .append("MavenDroolsController [policyContainer=")
969             .append(policyContainer.getName())
970             .append(":")
971             .append(", alive=")
972             .append(alive)
973             .append(", locked=")
974             .append(", modelClassLoaderHash=")
975             .append(modelClassLoaderHash)
976             .append("]");
977         return builder.toString();
978     }
979
980     // these may be overridden by junit tests
981
982     protected EventProtocolCoder getCoderManager() {
983         return EventProtocolCoderConstants.getManager();
984     }
985
986     protected OrderedServiceImpl<DroolsControllerFeatureApi> getDroolsProviders() {
987         return DroolsControllerFeatureApiConstants.getProviders();
988     }
989
990     protected PolicyContainer makePolicyContainer(String groupId, String artifactId, String version) {
991         return new PolicyContainer(groupId, artifactId, version);
992     }
993
994     protected boolean isClass(String className) {
995         return ReflectionUtil.isClass(this.policyContainer.getClassLoader(), className);
996     }
997 }