2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2023-2024 Nordix Foundation.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.drools.controller;
24 import com.google.re2j.Pattern;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
29 import java.util.Properties;
30 import lombok.NonNull;
31 import org.onap.policy.common.endpoints.event.comm.Topic;
32 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
33 import org.onap.policy.common.endpoints.event.comm.TopicSink;
34 import org.onap.policy.common.endpoints.event.comm.TopicSource;
35 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
36 import org.onap.policy.common.utils.services.FeatureApiUtils;
37 import org.onap.policy.drools.controller.internal.MavenDroolsController;
38 import org.onap.policy.drools.controller.internal.NullDroolsController;
39 import org.onap.policy.drools.features.DroolsControllerFeatureApi;
40 import org.onap.policy.drools.features.DroolsControllerFeatureApiConstants;
41 import org.onap.policy.drools.properties.DroolsPropertyConstants;
42 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
43 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration;
44 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomGsonCoder;
45 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.PotentialCoderFilter;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * Factory of Drools Controllers indexed by the Maven coordinates.
52 class IndexedDroolsControllerFactory implements DroolsControllerFactory {
54 private static final Logger logger = LoggerFactory.getLogger(IndexedDroolsControllerFactory.class);
55 private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
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 var 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 topics2DecodedClasses2Filters
252 .add(new TopicCoderFilterConfiguration(firstTopic, classes2Filters, customGsonCoder));
255 return topics2DecodedClasses2Filters;
258 private String getPropertyTopicPrefix(Topic topic) {
259 boolean isSource = topic instanceof TopicSource;
260 var commInfra = topic.getTopicCommInfrastructure();
261 if (commInfra == CommInfrastructure.UEB) {
263 return PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + ".";
265 return PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + ".";
267 } else if (commInfra == CommInfrastructure.NOOP) {
269 return PolicyEndPointProperties.PROPERTY_NOOP_SOURCE_TOPICS + ".";
271 return PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS + ".";
273 } else if (commInfra == CommInfrastructure.KAFKA) {
275 return PolicyEndPointProperties.PROPERTY_KAFKA_SOURCE_TOPICS + ".";
277 return PolicyEndPointProperties.PROPERTY_KAFKA_SINK_TOPICS + ".";
280 throw new IllegalArgumentException("Invalid Communication Infrastructure: " + commInfra);
284 private CustomGsonCoder getCustomCoder(Properties properties, String propertyPrefix) {
285 String customGson = properties.getProperty(propertyPrefix
286 + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_CUSTOM_MODEL_CODER_GSON_SUFFIX);
288 CustomGsonCoder customGsonCoder = null;
289 if (customGson != null && !customGson.isEmpty()) {
291 customGsonCoder = new CustomGsonCoder(customGson);
292 } catch (IllegalArgumentException e) {
293 logger.warn("{}: cannot create custom-gson-coder {} because of {}", this, customGson,
297 return customGsonCoder;
300 private List<PotentialCoderFilter> getFilterExpressions(Properties properties, String propertyPrefix,
301 @NonNull String eventClasses) {
303 List<PotentialCoderFilter> classes2Filters = new ArrayList<>();
304 for (String theClass : COMMA_SPACE_PAT.split(eventClasses)) {
306 // 4. for each coder class, get the filter expression
308 String filter = properties
309 .getProperty(propertyPrefix
310 + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX
311 + "." + theClass + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_FILTER_SUFFIX);
313 var class2Filters = new PotentialCoderFilter(theClass, new JsonProtocolFilter(filter));
314 classes2Filters.add(class2Filters);
317 return classes2Filters;
321 public void destroy(DroolsController controller) {
322 unmanage(controller);
327 public void destroy() {
328 List<DroolsController> controllers = this.inventory();
329 for (DroolsController controller : controllers) {
333 synchronized (this) {
334 this.droolsControllers.clear();
339 * unmanage the drools controller.
341 * @param controller the controller
343 protected void unmanage(DroolsController controller) {
344 if (controller == null) {
345 throw new IllegalArgumentException("No controller provided");
348 if (!controller.isBrained()) {
349 logger.info("Drools Controller is NOT OPERATIONAL - nothing to destroy");
353 String controllerId = controller.getGroupId() + ":" + controller.getArtifactId();
354 synchronized (this) {
355 if (!this.droolsControllers.containsKey(controllerId)) {
359 droolsControllers.remove(controllerId);
364 public void shutdown(DroolsController controller) {
365 this.unmanage(controller);
366 controller.shutdown();
370 public void shutdown() {
371 List<DroolsController> controllers = this.inventory();
372 for (DroolsController controller : controllers) {
373 controller.shutdown();
376 synchronized (this) {
377 this.droolsControllers.clear();
382 public DroolsController get(String groupId, String artifactId, String version) {
384 if (groupId == null || artifactId == null || groupId.isEmpty() || artifactId.isEmpty()) {
385 throw new IllegalArgumentException("Missing maven coordinates: " + groupId + ":" + artifactId);
388 String controllerId = groupId + ":" + artifactId;
390 synchronized (this) {
391 if (this.droolsControllers.containsKey(controllerId)) {
392 return droolsControllers.get(controllerId);
394 throw new IllegalStateException("DroolController for " + controllerId + " not found");
400 public List<DroolsController> inventory() {
401 return new ArrayList<>(this.droolsControllers.values());
405 public String toString() {
406 return "IndexedDroolsControllerFactory [#droolsControllers=" + droolsControllers.size() + "]";