2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
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;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.HashMap;
26 import java.util.List;
28 import java.util.Properties;
29 import org.onap.policy.common.endpoints.event.comm.Topic;
30 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
31 import org.onap.policy.common.endpoints.event.comm.TopicSink;
32 import org.onap.policy.common.endpoints.event.comm.TopicSource;
33 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
34 import org.onap.policy.common.utils.services.FeatureApiUtils;
35 import org.onap.policy.drools.controller.internal.MavenDroolsController;
36 import org.onap.policy.drools.controller.internal.NullDroolsController;
37 import org.onap.policy.drools.features.DroolsControllerFeatureApi;
38 import org.onap.policy.drools.features.DroolsControllerFeatureApiConstants;
39 import org.onap.policy.drools.properties.DroolsPropertyConstants;
40 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
41 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration;
42 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomGsonCoder;
43 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.PotentialCoderFilter;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * Factory of Drools Controllers indexed by the Maven coordinates.
50 class IndexedDroolsControllerFactory implements DroolsControllerFactory {
55 private static final Logger logger = LoggerFactory.getLogger(IndexedDroolsControllerFactory.class);
58 * Policy Controller Name Index.
60 protected Map<String, DroolsController> droolsControllers = new HashMap<>();
63 * Null Drools Controller.
65 protected NullDroolsController nullDroolsController = new NullDroolsController();
68 * Constructs the object.
70 public IndexedDroolsControllerFactory() {
72 /* Add a NULL controller which will always be present in the hash */
74 DroolsController controller = new NullDroolsController();
75 String controllerId = controller.getGroupId() + ":" + controller.getArtifactId();
78 droolsControllers.put(controllerId, controller);
83 public DroolsController build(Properties properties, List<? extends TopicSource> eventSources,
84 List<? extends TopicSink> eventSinks) throws LinkageError {
86 String groupId = properties.getProperty(DroolsPropertyConstants.RULES_GROUPID);
87 if (groupId == null || groupId.isEmpty()) {
88 groupId = DroolsControllerConstants.NO_GROUP_ID;
91 String artifactId = properties.getProperty(DroolsPropertyConstants.RULES_ARTIFACTID);
92 if (artifactId == null || artifactId.isEmpty()) {
93 artifactId = DroolsControllerConstants.NO_ARTIFACT_ID;
96 String version = properties.getProperty(DroolsPropertyConstants.RULES_VERSION);
97 if (version == null || version.isEmpty()) {
98 version = DroolsControllerConstants.NO_VERSION;
101 List<TopicCoderFilterConfiguration> topics2DecodedClasses2Filters = codersAndFilters(properties, eventSources);
102 List<TopicCoderFilterConfiguration> topics2EncodedClasses2Filters = codersAndFilters(properties, eventSinks);
104 return this.build(properties, groupId, artifactId, version,
105 topics2DecodedClasses2Filters, topics2EncodedClasses2Filters);
109 public DroolsController build(Properties properties, String newGroupId, String newArtifactId, String newVersion,
110 List<TopicCoderFilterConfiguration> decoderConfigurations,
111 List<TopicCoderFilterConfiguration> encoderConfigurations) throws LinkageError {
113 if (newGroupId == null || newGroupId.isEmpty()) {
114 throw new IllegalArgumentException("Missing maven group-id coordinate");
117 if (newArtifactId == null || newArtifactId.isEmpty()) {
118 throw new IllegalArgumentException("Missing maven artifact-id coordinate");
121 if (newVersion == null || newVersion.isEmpty()) {
122 throw new IllegalArgumentException("Missing maven version coordinate");
125 String controllerId = newGroupId + ":" + newArtifactId;
126 DroolsController controllerCopy = null;
127 synchronized (this) {
129 * The Null Drools Controller for no maven coordinates is always here so when no
130 * coordinates present, this is the return point
132 * assert (controllerCopy instanceof NullDroolsController)
134 if (droolsControllers.containsKey(controllerId)) {
135 controllerCopy = droolsControllers.get(controllerId);
136 if (controllerCopy.getVersion().equalsIgnoreCase(newVersion)) {
137 return controllerCopy;
142 if (controllerCopy != null) {
144 * a controller keyed by group id + artifact id exists but with different version =>
145 * version upgrade/downgrade
148 controllerCopy.updateToVersion(newGroupId, newArtifactId, newVersion, decoderConfigurations,
149 encoderConfigurations);
151 return controllerCopy;
154 /* new drools controller */
156 DroolsController controller = applyBeforeInstance(properties, newGroupId, newArtifactId, newVersion,
157 decoderConfigurations, encoderConfigurations);
159 if (controller == null) {
160 controller = new MavenDroolsController(newGroupId, newArtifactId, newVersion, decoderConfigurations,
161 encoderConfigurations);
164 synchronized (this) {
165 droolsControllers.put(controllerId, controller);
168 final DroolsController controllerFinal = controller;
170 FeatureApiUtils.apply(getProviders(),
171 feature -> feature.afterInstance(controllerFinal, properties),
172 (feature, ex) -> logger.error("feature {} ({}) afterInstance() of drools controller {}:{}:{} failed",
173 feature.getName(), feature.getSequenceNumber(),
174 newGroupId, newArtifactId, newVersion, ex));
179 private DroolsController applyBeforeInstance(Properties properties, String newGroupId, String newArtifactId,
180 String newVersion, List<TopicCoderFilterConfiguration> decoderConfigurations,
181 List<TopicCoderFilterConfiguration> encoderConfigurations) {
182 DroolsController controller = null;
183 for (DroolsControllerFeatureApi feature: getProviders()) {
185 controller = feature.beforeInstance(properties,
186 newGroupId, newArtifactId, newVersion,
187 decoderConfigurations, encoderConfigurations);
188 if (controller != null) {
189 logger.info("feature {} ({}) beforeInstance() has intercepted drools controller {}:{}:{}",
190 feature.getName(), feature.getSequenceNumber(),
191 newGroupId, newArtifactId, newVersion);
194 } catch (RuntimeException r) {
195 logger.error("feature {} ({}) beforeInstance() of drools controller {}:{}:{} failed",
196 feature.getName(), feature.getSequenceNumber(),
197 newGroupId, newArtifactId, newVersion, r);
203 protected List<DroolsControllerFeatureApi> getProviders() {
204 return DroolsControllerFeatureApiConstants.getProviders().getList();
208 * find out decoder classes and filters.
210 * @param properties properties with information about decoders
211 * @param topicEntities topic sources
212 * @return list of topics, each with associated decoder classes, each with a list of associated
214 * @throws IllegalArgumentException invalid input data
216 protected List<TopicCoderFilterConfiguration> codersAndFilters(Properties properties,
217 List<? extends Topic> topicEntities) {
219 List<TopicCoderFilterConfiguration> topics2DecodedClasses2Filters = new ArrayList<>();
221 if (topicEntities == null || topicEntities.isEmpty()) {
222 return topics2DecodedClasses2Filters;
225 for (Topic topic : topicEntities) {
227 // 1. first the topic
229 String firstTopic = topic.getTopic();
231 String propertyTopicEntityPrefix = getPropertyTopicPrefix(topic) + firstTopic;
233 // 2. check if there is a custom decoder for this topic that the user prefers to use
234 // instead of the ones provided in the platform
236 CustomGsonCoder customGsonCoder = getCustomCoder(properties, propertyTopicEntityPrefix);
238 // 3. second the list of classes associated with each topic
240 String eventClasses = properties
241 .getProperty(propertyTopicEntityPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX);
243 if (eventClasses == null || eventClasses.isEmpty()) {
244 logger.warn("There are no event classes for topic {}", firstTopic);
248 List<PotentialCoderFilter> classes2Filters =
249 getFilterExpressions(properties, propertyTopicEntityPrefix, eventClasses);
251 TopicCoderFilterConfiguration topic2Classes2Filters =
252 new TopicCoderFilterConfiguration(firstTopic, classes2Filters, customGsonCoder);
253 topics2DecodedClasses2Filters.add(topic2Classes2Filters);
256 return topics2DecodedClasses2Filters;
259 private String getPropertyTopicPrefix(Topic topic) {
260 boolean isSource = topic instanceof TopicSource;
261 CommInfrastructure commInfra = topic.getTopicCommInfrastructure();
262 if (commInfra == CommInfrastructure.UEB) {
264 return PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + ".";
266 return PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + ".";
268 } else if (commInfra == CommInfrastructure.DMAAP) {
270 return PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + ".";
272 return PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + ".";
274 } else if (commInfra == CommInfrastructure.NOOP) {
276 return PolicyEndPointProperties.PROPERTY_NOOP_SOURCE_TOPICS + ".";
278 return PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS + ".";
281 throw new IllegalArgumentException("Invalid Communication Infrastructure: " + commInfra);
285 private CustomGsonCoder getCustomCoder(Properties properties, String propertyPrefix) {
286 String customGson = properties.getProperty(propertyPrefix
287 + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_CUSTOM_MODEL_CODER_GSON_SUFFIX);
289 CustomGsonCoder customGsonCoder = null;
290 if (customGson != null && !customGson.isEmpty()) {
292 customGsonCoder = new CustomGsonCoder(customGson);
293 } catch (IllegalArgumentException e) {
294 logger.warn("{}: cannot create custom-gson-coder {} because of {}", this, customGson,
298 return customGsonCoder;
301 private List<PotentialCoderFilter> getFilterExpressions(Properties properties, String propertyPrefix,
302 String eventClasses) {
304 List<PotentialCoderFilter> classes2Filters = new ArrayList<>();
306 List<String> topicClasses = new ArrayList<>(Arrays.asList(eventClasses.split("\\s*,\\s*")));
308 for (String theClass : topicClasses) {
310 // 4. for each coder class, get the filter expression
312 String filter = properties
313 .getProperty(propertyPrefix
314 + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX
315 + "." + theClass + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_FILTER_SUFFIX);
317 JsonProtocolFilter protocolFilter = new JsonProtocolFilter(filter);
318 PotentialCoderFilter class2Filters = new PotentialCoderFilter(theClass, protocolFilter);
319 classes2Filters.add(class2Filters);
322 return classes2Filters;
326 public void destroy(DroolsController controller) {
327 unmanage(controller);
332 public void destroy() {
333 List<DroolsController> controllers = this.inventory();
334 for (DroolsController controller : controllers) {
338 synchronized (this) {
339 this.droolsControllers.clear();
344 * unmanage the drools controller.
346 * @param controller the controller
348 protected void unmanage(DroolsController controller) {
349 if (controller == null) {
350 throw new IllegalArgumentException("No controller provided");
353 if (!controller.isBrained()) {
354 logger.info("Drools Controller is NOT OPERATIONAL - nothing to destroy");
358 String controllerId = controller.getGroupId() + ":" + controller.getArtifactId();
359 synchronized (this) {
360 if (!this.droolsControllers.containsKey(controllerId)) {
364 droolsControllers.remove(controllerId);
369 public void shutdown(DroolsController controller) {
370 this.unmanage(controller);
371 controller.shutdown();
375 public void shutdown() {
376 List<DroolsController> controllers = this.inventory();
377 for (DroolsController controller : controllers) {
378 controller.shutdown();
381 synchronized (this) {
382 this.droolsControllers.clear();
387 public DroolsController get(String groupId, String artifactId, String version) {
389 if (groupId == null || artifactId == null || groupId.isEmpty() || artifactId.isEmpty()) {
390 throw new IllegalArgumentException("Missing maven coordinates: " + groupId + ":" + artifactId);
393 String controllerId = groupId + ":" + artifactId;
395 synchronized (this) {
396 if (this.droolsControllers.containsKey(controllerId)) {
397 return droolsControllers.get(controllerId);
399 throw new IllegalStateException("DroolController for " + controllerId + " not found");
405 public List<DroolsController> inventory() {
406 return new ArrayList<>(this.droolsControllers.values());
410 public String toString() {
411 StringBuilder builder = new StringBuilder();
412 builder.append("IndexedDroolsControllerFactory [#droolsControllers=").append(droolsControllers.size())
414 return builder.toString();