2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.drools.controller.internal;
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;
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;
55 * Maven-based Drools Controller that interacts with the
56 * policy-core PolicyContainer and PolicySession to manage
57 * Drools containers instantiated using Maven.
59 public class MavenDroolsController implements DroolsController {
64 private static Logger logger = LoggerFactory.getLogger(MavenDroolsController.class);
67 * Policy Container, the access object to the policy-core layer.
70 protected final PolicyContainer policyContainer;
73 * alive status of this drools controller,
74 * reflects invocation of start()/stop() only.
76 protected volatile boolean alive = false;
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
85 protected volatile boolean locked = false;
88 * list of topics, each with associated decoder classes, each
89 * with a list of associated filters.
91 protected List<TopicCoderFilterConfiguration> decoderConfigurations;
94 * list of topics, each with associated encoder classes, each
95 * with a list of associated filters.
97 protected List<TopicCoderFilterConfiguration> encoderConfigurations;
100 * recent source events processed.
102 protected final CircularFifoQueue<Object> recentSourceEvents = new CircularFifoQueue<>(10);
105 * recent sink events processed.
107 protected final CircularFifoQueue<String> recentSinkEvents = new CircularFifoQueue<>(10);
110 * original Drools Model/Rules classloader hash.
112 protected int modelClassLoaderHash;
115 * Expanded version of the constructor.
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
123 * @throws IllegalArgumentException invalid arguments passed in
125 public MavenDroolsController(String groupId,
128 List<TopicCoderFilterConfiguration> decoderConfigurations,
129 List<TopicCoderFilterConfiguration> encoderConfigurations) {
131 logger.info("drools-controller instantiation [{}:{}:{}]", groupId, artifactId, version);
133 if (groupId == null || groupId.isEmpty()) {
134 throw new IllegalArgumentException("Missing maven group-id coordinate");
137 if (artifactId == null || artifactId.isEmpty()) {
138 throw new IllegalArgumentException("Missing maven artifact-id coordinate");
141 if (version == null || version.isEmpty()) {
142 throw new IllegalArgumentException("Missing maven version coordinate");
145 this.policyContainer = new PolicyContainer(groupId, artifactId, version);
146 this.init(decoderConfigurations, encoderConfigurations);
148 logger.debug("{}: instantiation completed ", this);
152 * init encoding/decoding configuration.
154 * @param decoderConfigurations list of topic -> decoders -> filters mapping
155 * @param encoderConfigurations list of topic -> encoders -> filters mapping
157 protected void init(List<TopicCoderFilterConfiguration> decoderConfigurations,
158 List<TopicCoderFilterConfiguration> encoderConfigurations) {
160 this.decoderConfigurations = decoderConfigurations;
161 this.encoderConfigurations = encoderConfigurations;
163 this.initCoders(decoderConfigurations, true);
164 this.initCoders(encoderConfigurations, false);
166 this.modelClassLoaderHash = this.policyContainer.getClassLoader().hashCode();
170 public void updateToVersion(String newGroupId, String newArtifactId, String newVersion,
171 List<TopicCoderFilterConfiguration> decoderConfigurations,
172 List<TopicCoderFilterConfiguration> encoderConfigurations)
173 throws LinkageError {
175 logger.info("updating version -> [{}:{}:{}]", newGroupId, newArtifactId, newVersion);
177 if (newGroupId == null || newGroupId.isEmpty()) {
178 throw new IllegalArgumentException("Missing maven group-id coordinate");
181 if (newArtifactId == null || newArtifactId.isEmpty()) {
182 throw new IllegalArgumentException("Missing maven artifact-id coordinate");
185 if (newVersion == null || newVersion.isEmpty()) {
186 throw new IllegalArgumentException("Missing maven version coordinate");
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 + ":"
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);
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);
214 String messages = this.policyContainer.updateToVersion(newVersion);
215 if (logger.isWarnEnabled()) {
216 logger.warn("{} UPGRADE results: {}", this, messages);
220 * If all sucessful (can load new container), now we can remove all coders from previous sessions
227 this.init(decoderConfigurations, encoderConfigurations);
229 if (logger.isInfoEnabled()) {
230 logger.info("UPDATE-TO-VERSION: completed " + this);
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.
239 * @param coderConfigurations list of topic -> decoders -> filters mapping
241 protected void initCoders(List<TopicCoderFilterConfiguration> coderConfigurations,
244 if (logger.isInfoEnabled()) {
245 logger.info("INIT-CODERS: " + this);
248 if (coderConfigurations == null) {
253 for (TopicCoderFilterConfiguration coderConfig: coderConfigurations) {
254 String topic = coderConfig.getTopic();
256 CustomGsonCoder customGsonCoder = coderConfig.getCustomGsonCoder();
257 if (coderConfig.getCustomGsonCoder() != null
258 && coderConfig.getCustomGsonCoder().getClassContainer() != null
259 && !coderConfig.getCustomGsonCoder().getClassContainer().isEmpty()) {
261 String customGsonCoderClass = coderConfig.getCustomGsonCoder().getClassContainer();
262 if (!ReflectionUtil.isClass(this.policyContainer.getClassLoader(),
263 customGsonCoderClass)) {
264 throw makeRetrieveEx(customGsonCoderClass);
266 if (logger.isInfoEnabled()) {
267 logClassFetched(customGsonCoderClass);
272 List<PotentialCoderFilter> coderFilters = coderConfig.getCoderFilters();
273 if (coderFilters == null || coderFilters.isEmpty()) {
277 for (PotentialCoderFilter coderFilter : coderFilters) {
278 String potentialCodedClass = coderFilter.getCodedClass();
279 JsonProtocolFilter protocolFilter = coderFilter.getFilter();
281 if (!ReflectionUtil.isClass(this.policyContainer.getClassLoader(),
282 potentialCodedClass)) {
283 throw makeRetrieveEx(potentialCodedClass);
285 if (logger.isInfoEnabled()) {
286 logClassFetched(potentialCodedClass);
291 EventProtocolCoder.manager.addDecoder(EventProtocolParams.builder()
292 .groupId(this.getGroupId())
293 .artifactId(this.getArtifactId())
295 .eventClass(potentialCodedClass)
296 .protocolFilter(protocolFilter)
297 .customGsonCoder(customGsonCoder)
298 .modelClassLoaderHash(this.policyContainer.getClassLoader().hashCode()));
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()));
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
316 private IllegalArgumentException makeRetrieveEx(String itemName) {
317 logger.error("{} cannot be retrieved", itemName);
318 return new IllegalArgumentException(itemName + " cannot be retrieved");
322 * Logs the name of the class that was fetched.
323 * @param className class name fetched
325 private void logClassFetched(String className) {
326 logger.info("CLASS FETCHED {}", className);
333 protected void removeDecoders() {
334 if (logger.isInfoEnabled()) {
335 logger.info("REMOVE-DECODERS: {}", this);
338 if (this.decoderConfigurations == null) {
343 for (TopicCoderFilterConfiguration coderConfig: decoderConfigurations) {
344 String topic = coderConfig.getTopic();
345 EventProtocolCoder.manager.removeDecoders(this.getGroupId(), this.getArtifactId(), topic);
352 protected void removeEncoders() {
354 if (logger.isInfoEnabled()) {
355 logger.info("REMOVE-ENCODERS: {}", this);
358 if (this.encoderConfigurations == null) {
362 for (TopicCoderFilterConfiguration coderConfig: encoderConfigurations) {
363 String topic = coderConfig.getTopic();
364 EventProtocolCoder.manager.removeEncoders(this.getGroupId(), this.getArtifactId(), topic);
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());
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());
384 if (logger.isWarnEnabled()) {
385 logger.warn(this + coderClass.getCanonicalName() + " class loaders don't match "
386 + coderClass.getClassLoader() + " vs "
387 + this.policyContainer.getClassLoader());
394 public boolean start() {
396 if (logger.isInfoEnabled()) {
397 logger.info("START: {}", this);
400 synchronized (this) {
407 return this.policyContainer.start();
411 public boolean stop() {
413 logger.info("STOP: {}", this);
415 synchronized (this) {
422 return this.policyContainer.stop();
426 public void shutdown() {
427 logger.info("{}: SHUTDOWN", this);
432 } catch (Exception e) {
433 logger.error("{} SHUTDOWN FAILED because of {}", this, e.getMessage(), e);
435 this.policyContainer.shutdown();
442 logger.info("{}: HALT", this);
447 } catch (Exception e) {
448 logger.error("{} HALT FAILED because of {}", this, e.getMessage(), e);
450 this.policyContainer.destroy();
455 * removes this drools controllers and encoders and decoders from operation.
457 protected void removeCoders() {
458 logger.info("{}: REMOVE-CODERS", this);
461 this.removeDecoders();
462 } catch (IllegalArgumentException e) {
463 logger.error("{} REMOVE-DECODERS FAILED because of {}", this, e.getMessage(), e);
467 this.removeEncoders();
468 } catch (IllegalArgumentException e) {
469 logger.error("{} REMOVE-ENCODERS FAILED because of {}", this, e.getMessage(), e);
474 public boolean isAlive() {
479 public boolean offer(String topic, String event) {
480 logger.debug("{}: OFFER: {} <- {}", this, topic, event);
489 // 0. Check if the policy container has any sessions
491 if (this.policyContainer.getPolicySessions().isEmpty()) {
496 // 1. Now, check if this topic has a decoder:
498 if (!EventProtocolCoder.manager.isDecodingSupported(this.getGroupId(),
499 this.getArtifactId(),
502 logger.warn("{}: DECODING-UNSUPPORTED {}:{}:{}", this,
503 topic, this.getGroupId(), this.getArtifactId());
511 anEvent = EventProtocolCoder.manager.decode(this.getGroupId(),
512 this.getArtifactId(),
515 } catch (UnsupportedOperationException uoe) {
516 logger.debug("{}: DECODE FAILED: {} <- {} because of {}", this, topic,
517 event, uoe.getMessage(), uoe);
519 } catch (Exception e) {
520 logger.warn("{}: DECODE FAILED: {} <- {} because of {}", this, topic,
521 event, e.getMessage(), e);
525 synchronized (this.recentSourceEvents) {
526 this.recentSourceEvents.add(anEvent);
529 // increment event count for Nagios monitoring
530 PdpJmx.getInstance().updateOccured();
534 if (logger.isInfoEnabled()) {
535 logger.info("{} BROADCAST-INJECT of {} FROM {} INTO {}",
536 this, event, topic, this.policyContainer.getName());
539 for (DroolsControllerFeatureAPI feature : DroolsControllerFeatureAPI.providers.getList()) {
541 if (feature.beforeInsert(this, anEvent)) {
544 } catch (Exception e) {
545 logger.error("{}: feature {} before-insert failure because of {}",
546 this, feature.getClass().getName(), e.getMessage(), e);
550 boolean successInject = this.policyContainer.insertAll(anEvent);
551 if (!successInject) {
552 logger.warn(this + "Failed to inject into PolicyContainer {}", this.getSessionNames());
555 for (DroolsControllerFeatureAPI feature : DroolsControllerFeatureAPI.providers.getList()) {
557 if (feature.afterInsert(this, anEvent, successInject)) {
560 } catch (Exception e) {
561 logger.error("{}: feature {} after-insert failure because of {}",
562 this, feature.getClass().getName(), e.getMessage(), e);
570 public boolean deliver(TopicSink sink, Object event) {
572 if (logger.isInfoEnabled()) {
573 logger.info("{}DELIVER: {} FROM {} TO {}", this, event, this, sink);
577 throw new IllegalArgumentException(this + " invalid sink");
581 throw new IllegalArgumentException(this + " invalid event");
585 throw new IllegalStateException(this + " is locked");
589 throw new IllegalStateException(this + " is stopped");
593 EventProtocolCoder.manager.encode(sink.getTopic(), event, this);
595 synchronized (this.recentSinkEvents) {
596 this.recentSinkEvents.add(json);
599 return sink.send(json);
604 public String getVersion() {
605 return this.policyContainer.getVersion();
609 public String getArtifactId() {
610 return this.policyContainer.getArtifactId();
614 public String getGroupId() {
615 return this.policyContainer.getGroupId();
619 * Get model class loader hash.
621 * @return the modelClassLoaderHash
623 public int getModelClassLoaderHash() {
624 return modelClassLoaderHash;
628 public synchronized boolean lock() {
629 logger.info("LOCK: {}", this);
636 public synchronized boolean unlock() {
637 logger.info("UNLOCK: {}", this);
644 public boolean isLocked() {
650 public PolicyContainer getContainer() {
651 return this.policyContainer;
654 @JsonProperty("sessions")
656 public List<String> getSessionNames() {
657 return getSessionNames(true);
663 * @param abbreviated true for the short form, otherwise the long form
664 * @return session names
666 protected List<String> getSessionNames(boolean abbreviated) {
667 List<String> sessionNames = new ArrayList<>();
669 for (PolicySession session: this.policyContainer.getPolicySessions()) {
671 sessionNames.add(session.getName());
673 sessionNames.add(session.getFullName());
676 } catch (Exception e) {
677 logger.warn("Can't retrieve CORE sessions: " + e.getMessage(), e);
678 sessionNames.add(e.getMessage());
683 @JsonProperty("sessionCoordinates")
685 public List<String> getCanonicalSessionNames() {
686 return getSessionNames(false);
690 public List<String> getBaseDomainNames() {
691 return new ArrayList<>(this.policyContainer.getKieContainer().getKieBaseNames());
695 * provides the underlying core layer container sessions.
697 * @return the attached Policy Container
699 protected List<PolicySession> getSessions() {
700 List<PolicySession> sessions = new ArrayList<>();
701 sessions.addAll(this.policyContainer.getPolicySessions());
706 * provides the underlying core layer container session with name sessionName.
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
713 protected PolicySession getSession(String sessionName) {
714 if (sessionName == null || sessionName.isEmpty()) {
715 throw new IllegalArgumentException("A Session Name must be provided");
718 List<PolicySession> sessions = this.getSessions();
719 for (PolicySession session : sessions) {
720 if (sessionName.equals(session.getName()) || sessionName.equals(session.getFullName())) {
725 throw invalidSessNameEx(sessionName);
728 private IllegalArgumentException invalidSessNameEx(String sessionName) {
729 return new IllegalArgumentException("Invalid Session Name: " + sessionName);
733 public Map<String,Integer> factClassNames(String sessionName) {
734 if (sessionName == null || sessionName.isEmpty()) {
735 throw invalidSessNameEx(sessionName);
738 Map<String,Integer> classNames = new HashMap<>();
740 PolicySession session = getSession(sessionName);
741 KieSession kieSession = session.getKieSession();
743 Collection<FactHandle> facts = session.getKieSession().getFactHandles();
744 for (FactHandle fact : facts) {
746 String className = kieSession.getObject(fact).getClass().getName();
747 if (classNames.containsKey(className)) {
748 classNames.put(className, classNames.get(className) + 1);
750 classNames.put(className, 1);
752 } catch (Exception e) {
753 logger.warn("Object cannot be retrieved from fact {}", fact, e);
761 public long factCount(String sessionName) {
762 if (sessionName == null || sessionName.isEmpty()) {
763 throw invalidSessNameEx(sessionName);
766 PolicySession session = getSession(sessionName);
767 return session.getKieSession().getFactCount();
771 public List<Object> facts(String sessionName, String className, boolean delete) {
772 if (sessionName == null || sessionName.isEmpty()) {
773 throw invalidSessNameEx(sessionName);
776 if (className == null || className.isEmpty()) {
777 throw new IllegalArgumentException("Invalid Class Name: " + className);
781 ReflectionUtil.fetchClass(this.policyContainer.getClassLoader(), className);
782 if (factClass == null) {
783 throw new IllegalArgumentException("Class cannot be fetched in model's classloader: " + className);
786 PolicySession session = getSession(sessionName);
787 KieSession kieSession = session.getKieSession();
789 List<Object> factObjects = new ArrayList<>();
791 Collection<FactHandle> factHandles = kieSession.getFactHandles(new ClassObjectFilter(factClass));
792 for (FactHandle factHandle : factHandles) {
794 factObjects.add(kieSession.getObject(factHandle));
796 kieSession.delete(factHandle);
798 } catch (Exception e) {
799 logger.warn("Object cannot be retrieved from fact {}", factHandle, e);
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);
813 if (queryName == null || queryName.isEmpty()) {
814 throw new IllegalArgumentException("Invalid Query Name: " + queryName);
817 if (queriedEntity == null || queriedEntity.isEmpty()) {
818 throw new IllegalArgumentException("Invalid Queried Entity: " + queriedEntity);
821 PolicySession session = getSession(sessionName);
822 KieSession kieSession = session.getKieSession();
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)) {
834 throw new IllegalArgumentException("Invalid Query Name: " + queryName);
837 List<Object> factObjects = new ArrayList<>();
839 QueryResults queryResults = kieSession.getQueryResults(queryName, queryParams);
840 for (QueryResultsRow row : queryResults) {
842 factObjects.add(row.get(queriedEntity));
844 kieSession.delete(row.getFactHandle(queriedEntity));
846 } catch (Exception e) {
847 logger.warn("Object cannot be retrieved from row: {}", row, e);
855 public Class<?> fetchModelClass(String className) {
856 return ReflectionUtil.fetchClass(this.policyContainer.getClassLoader(), className);
860 * Get recent source events.
862 * @return the recentSourceEvents
865 public Object[] getRecentSourceEvents() {
866 synchronized (this.recentSourceEvents) {
867 Object[] events = new Object[recentSourceEvents.size()];
868 return recentSourceEvents.toArray(events);
873 * Get recent sink events.
875 * @return the recentSinkEvents
878 public String[] getRecentSinkEvents() {
879 synchronized (this.recentSinkEvents) {
880 String[] events = new String[recentSinkEvents.size()];
881 return recentSinkEvents.toArray(events);
886 public boolean isBrained() {
892 public String toString() {
893 StringBuilder builder = new StringBuilder();
895 .append("MavenDroolsController [policyContainer=")
896 .append((policyContainer != null) ? policyContainer.getName() : "NULL")
901 .append(", modelClassLoaderHash=")
902 .append(modelClassLoaderHash)
904 return builder.toString();