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