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.drools.controller.internal.MavenDroolsController;
35 import org.onap.policy.drools.controller.internal.NullDroolsController;
36 import org.onap.policy.drools.features.DroolsControllerFeatureApi;
37 import org.onap.policy.drools.features.DroolsControllerFeatureApiConstants;
38 import org.onap.policy.drools.properties.DroolsPropertyConstants;
39 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
40 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration;
41 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomGsonCoder;
42 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.PotentialCoderFilter;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * Factory of Drools Controllers indexed by the Maven coordinates.
49 class IndexedDroolsControllerFactory implements DroolsControllerFactory {
54 private static final Logger logger = LoggerFactory.getLogger(IndexedDroolsControllerFactory.class);
57 * Policy Controller Name Index.
59 protected Map<String, DroolsController> droolsControllers = new HashMap<>();
62 * Null Drools Controller.
64 protected NullDroolsController nullDroolsController = new NullDroolsController();
67 * Constructs the object.
69 public IndexedDroolsControllerFactory() {
71 /* Add a NULL controller which will always be present in the hash */
73 DroolsController controller = new NullDroolsController();
74 String controllerId = controller.getGroupId() + ":" + controller.getArtifactId();
77 droolsControllers.put(controllerId, controller);
82 public DroolsController build(Properties properties, List<? extends TopicSource> eventSources,
83 List<? extends TopicSink> eventSinks) throws LinkageError {
85 String groupId = properties.getProperty(DroolsPropertyConstants.RULES_GROUPID);
86 if (groupId == null || groupId.isEmpty()) {
87 groupId = DroolsControllerConstants.NO_GROUP_ID;
90 String artifactId = properties.getProperty(DroolsPropertyConstants.RULES_ARTIFACTID);
91 if (artifactId == null || artifactId.isEmpty()) {
92 artifactId = DroolsControllerConstants.NO_ARTIFACT_ID;
95 String version = properties.getProperty(DroolsPropertyConstants.RULES_VERSION);
96 if (version == null || version.isEmpty()) {
97 version = DroolsControllerConstants.NO_VERSION;
100 List<TopicCoderFilterConfiguration> topics2DecodedClasses2Filters = codersAndFilters(properties, eventSources);
101 List<TopicCoderFilterConfiguration> topics2EncodedClasses2Filters = codersAndFilters(properties, eventSinks);
103 return this.build(properties, groupId, artifactId, version,
104 topics2DecodedClasses2Filters, topics2EncodedClasses2Filters);
108 public DroolsController build(Properties properties, String newGroupId, String newArtifactId, String newVersion,
109 List<TopicCoderFilterConfiguration> decoderConfigurations,
110 List<TopicCoderFilterConfiguration> encoderConfigurations) throws LinkageError {
112 if (newGroupId == null || newGroupId.isEmpty()) {
113 throw new IllegalArgumentException("Missing maven group-id coordinate");
116 if (newArtifactId == null || newArtifactId.isEmpty()) {
117 throw new IllegalArgumentException("Missing maven artifact-id coordinate");
120 if (newVersion == null || newVersion.isEmpty()) {
121 throw new IllegalArgumentException("Missing maven version coordinate");
124 String controllerId = newGroupId + ":" + newArtifactId;
125 DroolsController controllerCopy = null;
126 synchronized (this) {
128 * The Null Drools Controller for no maven coordinates is always here so when no
129 * coordinates present, this is the return point
131 * assert (controllerCopy instanceof NullDroolsController)
133 if (droolsControllers.containsKey(controllerId)) {
134 controllerCopy = droolsControllers.get(controllerId);
135 if (controllerCopy.getVersion().equalsIgnoreCase(newVersion)) {
136 return controllerCopy;
141 if (controllerCopy != null) {
143 * a controller keyed by group id + artifact id exists but with different version =>
144 * version upgrade/downgrade
147 controllerCopy.updateToVersion(newGroupId, newArtifactId, newVersion, decoderConfigurations,
148 encoderConfigurations);
150 return controllerCopy;
153 /* new drools controller */
155 DroolsController controller = null;
156 for (DroolsControllerFeatureApi feature: getProviders()) {
158 controller = feature.beforeInstance(properties,
159 newGroupId, newArtifactId, newVersion,
160 decoderConfigurations, encoderConfigurations);
161 if (controller != null) {
162 logger.info("feature {} ({}) beforeInstance() has intercepted drools controller {}:{}:{}",
163 feature.getName(), feature.getSequenceNumber(),
164 newGroupId, newArtifactId, newVersion);
167 } catch (RuntimeException r) {
168 logger.error("feature {} ({}) beforeInstance() of drools controller {}:{}:{} failed",
169 feature.getName(), feature.getSequenceNumber(),
170 newGroupId, newArtifactId, newVersion, r);
174 if (controller == null) {
175 controller = new MavenDroolsController(newGroupId, newArtifactId, newVersion, decoderConfigurations,
176 encoderConfigurations);
179 synchronized (this) {
180 droolsControllers.put(controllerId, controller);
183 for (DroolsControllerFeatureApi feature: getProviders()) {
185 feature.afterInstance(controller, properties);
186 } catch (RuntimeException r) {
187 logger.error("feature {} ({}) afterInstance() of drools controller {}:{}:{} failed",
188 feature.getName(), feature.getSequenceNumber(),
189 newGroupId, newArtifactId, newVersion, r);
196 protected List<DroolsControllerFeatureApi> getProviders() {
197 return DroolsControllerFeatureApiConstants.getProviders().getList();
201 * find out decoder classes and filters.
203 * @param properties properties with information about decoders
204 * @param topicEntities topic sources
205 * @return list of topics, each with associated decoder classes, each with a list of associated
207 * @throws IllegalArgumentException invalid input data
209 protected List<TopicCoderFilterConfiguration> codersAndFilters(Properties properties,
210 List<? extends Topic> topicEntities) {
212 List<TopicCoderFilterConfiguration> topics2DecodedClasses2Filters = new ArrayList<>();
214 if (topicEntities == null || topicEntities.isEmpty()) {
215 return topics2DecodedClasses2Filters;
218 for (Topic topic : topicEntities) {
220 // 1. first the topic
222 String firstTopic = topic.getTopic();
224 String propertyTopicEntityPrefix = getPropertyTopicPrefix(topic) + firstTopic;
226 // 2. check if there is a custom decoder for this topic that the user prefers to use
227 // instead of the ones provided in the platform
229 CustomGsonCoder customGsonCoder = getCustomCoder(properties, propertyTopicEntityPrefix);
231 // 3. second the list of classes associated with each topic
233 String eventClasses = properties
234 .getProperty(propertyTopicEntityPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX);
236 if (eventClasses == null || eventClasses.isEmpty()) {
237 logger.warn("There are no event classes for topic {}", firstTopic);
241 List<PotentialCoderFilter> classes2Filters =
242 getFilterExpressions(properties, propertyTopicEntityPrefix, eventClasses);
244 TopicCoderFilterConfiguration topic2Classes2Filters =
245 new TopicCoderFilterConfiguration(firstTopic, classes2Filters, customGsonCoder);
246 topics2DecodedClasses2Filters.add(topic2Classes2Filters);
249 return topics2DecodedClasses2Filters;
252 private String getPropertyTopicPrefix(Topic topic) {
253 boolean isSource = topic instanceof TopicSource;
254 CommInfrastructure commInfra = topic.getTopicCommInfrastructure();
255 if (commInfra == CommInfrastructure.UEB) {
257 return PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + ".";
259 return PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + ".";
261 } else if (commInfra == CommInfrastructure.DMAAP) {
263 return PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + ".";
265 return PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + ".";
267 } else if (commInfra == CommInfrastructure.NOOP) {
269 return PolicyEndPointProperties.PROPERTY_NOOP_SOURCE_TOPICS + ".";
271 return PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS + ".";
274 throw new IllegalArgumentException("Invalid Communication Infrastructure: " + commInfra);
278 private CustomGsonCoder getCustomCoder(Properties properties, String propertyPrefix) {
279 String customGson = properties.getProperty(propertyPrefix
280 + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_CUSTOM_MODEL_CODER_GSON_SUFFIX);
282 CustomGsonCoder customGsonCoder = null;
283 if (customGson != null && !customGson.isEmpty()) {
285 customGsonCoder = new CustomGsonCoder(customGson);
286 } catch (IllegalArgumentException e) {
287 logger.warn("{}: cannot create custom-gson-coder {} because of {}", this, customGson,
291 return customGsonCoder;
294 private List<PotentialCoderFilter> getFilterExpressions(Properties properties, String propertyPrefix,
295 String eventClasses) {
297 List<PotentialCoderFilter> classes2Filters = new ArrayList<>();
299 List<String> topicClasses = new ArrayList<>(Arrays.asList(eventClasses.split("\\s*,\\s*")));
301 for (String theClass : topicClasses) {
303 // 4. for each coder class, get the filter expression
305 String filter = properties
306 .getProperty(propertyPrefix
307 + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX
308 + "." + theClass + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_FILTER_SUFFIX);
310 JsonProtocolFilter protocolFilter = new JsonProtocolFilter(filter);
311 PotentialCoderFilter class2Filters = new PotentialCoderFilter(theClass, protocolFilter);
312 classes2Filters.add(class2Filters);
315 return classes2Filters;
319 public void destroy(DroolsController controller) {
320 unmanage(controller);
325 public void destroy() {
326 List<DroolsController> controllers = this.inventory();
327 for (DroolsController controller : controllers) {
331 synchronized (this) {
332 this.droolsControllers.clear();
337 * unmanage the drools controller.
339 * @param controller the controller
341 protected void unmanage(DroolsController controller) {
342 if (controller == null) {
343 throw new IllegalArgumentException("No controller provided");
346 if (!controller.isBrained()) {
347 logger.info("Drools Controller is NOT OPERATIONAL - nothing to destroy");
351 String controllerId = controller.getGroupId() + ":" + controller.getArtifactId();
352 synchronized (this) {
353 if (!this.droolsControllers.containsKey(controllerId)) {
357 droolsControllers.remove(controllerId);
362 public void shutdown(DroolsController controller) {
363 this.unmanage(controller);
364 controller.shutdown();
368 public void shutdown() {
369 List<DroolsController> controllers = this.inventory();
370 for (DroolsController controller : controllers) {
371 controller.shutdown();
374 synchronized (this) {
375 this.droolsControllers.clear();
380 public DroolsController get(String groupId, String artifactId, String version) {
382 if (groupId == null || artifactId == null || groupId.isEmpty() || artifactId.isEmpty()) {
383 throw new IllegalArgumentException("Missing maven coordinates: " + groupId + ":" + artifactId);
386 String controllerId = groupId + ":" + artifactId;
388 synchronized (this) {
389 if (this.droolsControllers.containsKey(controllerId)) {
390 return droolsControllers.get(controllerId);
392 throw new IllegalStateException("DroolController for " + controllerId + " not found");
398 public List<DroolsController> inventory() {
399 return new ArrayList<>(this.droolsControllers.values());
403 public String toString() {
404 StringBuilder builder = new StringBuilder();
405 builder.append("IndexedDroolsControllerFactory [#droolsControllers=").append(droolsControllers.size())
407 return builder.toString();