Removing deprecated DMAAP library
[policy/drools-pdp.git] / policy-management / src / main / java / org / onap / policy / drools / controller / IndexedDroolsControllerFactory.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21
22 package org.onap.policy.drools.controller;
23
24 import com.google.re2j.Pattern;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
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;
48
49 /**
50  * Factory of Drools Controllers indexed by the Maven coordinates.
51  */
52 class IndexedDroolsControllerFactory implements DroolsControllerFactory {
53
54     private static final Logger logger = LoggerFactory.getLogger(IndexedDroolsControllerFactory.class);
55     private static final Pattern COMMA_SPACE_PAT = Pattern.compile("\\s*,\\s*");
56
57     /**
58      * Policy Controller Name Index.
59      */
60     protected Map<String, DroolsController> droolsControllers = new HashMap<>();
61
62     /**
63      * Null Drools Controller.
64      */
65     protected NullDroolsController nullDroolsController = new NullDroolsController();
66
67     /**
68      * Constructs the object.
69      */
70     public IndexedDroolsControllerFactory() {
71
72         /* Add a NULL controller which will always be present in the hash */
73
74         DroolsController controller = new NullDroolsController();
75         String controllerId = controller.getGroupId() + ":" + controller.getArtifactId();
76
77         synchronized (this) {
78             droolsControllers.put(controllerId, controller);
79         }
80     }
81
82     @Override
83     public DroolsController build(Properties properties, List<? extends TopicSource> eventSources,
84             List<? extends TopicSink> eventSinks) throws LinkageError {
85
86         String groupId = properties.getProperty(DroolsPropertyConstants.RULES_GROUPID);
87         if (groupId == null || groupId.isEmpty()) {
88             groupId = DroolsControllerConstants.NO_GROUP_ID;
89         }
90
91         String artifactId = properties.getProperty(DroolsPropertyConstants.RULES_ARTIFACTID);
92         if (artifactId == null || artifactId.isEmpty()) {
93             artifactId = DroolsControllerConstants.NO_ARTIFACT_ID;
94         }
95
96         String version = properties.getProperty(DroolsPropertyConstants.RULES_VERSION);
97         if (version == null || version.isEmpty()) {
98             version = DroolsControllerConstants.NO_VERSION;
99         }
100
101         List<TopicCoderFilterConfiguration> topics2DecodedClasses2Filters = codersAndFilters(properties, eventSources);
102         List<TopicCoderFilterConfiguration> topics2EncodedClasses2Filters = codersAndFilters(properties, eventSinks);
103
104         return this.build(properties, groupId, artifactId, version,
105                 topics2DecodedClasses2Filters, topics2EncodedClasses2Filters);
106     }
107
108     @Override
109     public DroolsController build(Properties properties, String newGroupId, String newArtifactId, String newVersion,
110             List<TopicCoderFilterConfiguration> decoderConfigurations,
111             List<TopicCoderFilterConfiguration> encoderConfigurations) throws LinkageError {
112
113         if (newGroupId == null || newGroupId.isEmpty()) {
114             throw new IllegalArgumentException("Missing maven group-id coordinate");
115         }
116
117         if (newArtifactId == null || newArtifactId.isEmpty()) {
118             throw new IllegalArgumentException("Missing maven artifact-id coordinate");
119         }
120
121         if (newVersion == null || newVersion.isEmpty()) {
122             throw new IllegalArgumentException("Missing maven version coordinate");
123         }
124
125         String controllerId = newGroupId + ":" + newArtifactId;
126         DroolsController controllerCopy = null;
127         synchronized (this) {
128             /*
129              * The Null Drools Controller for no maven coordinates is always here so when no
130              * coordinates present, this is the return point
131              *
132              * assert (controllerCopy instanceof NullDroolsController)
133              */
134             if (droolsControllers.containsKey(controllerId)) {
135                 controllerCopy = droolsControllers.get(controllerId);
136                 if (controllerCopy.getVersion().equalsIgnoreCase(newVersion)) {
137                     return controllerCopy;
138                 }
139             }
140         }
141
142         if (controllerCopy != null) {
143             /*
144              * a controller keyed by group id + artifact id exists but with different version =>
145              * version upgrade/downgrade
146              */
147
148             controllerCopy.updateToVersion(newGroupId, newArtifactId, newVersion, decoderConfigurations,
149                     encoderConfigurations);
150
151             return controllerCopy;
152         }
153
154         /* new drools controller */
155
156         DroolsController controller = applyBeforeInstance(properties, newGroupId, newArtifactId, newVersion,
157                         decoderConfigurations, encoderConfigurations);
158
159         if (controller == null) {
160             controller = new MavenDroolsController(newGroupId, newArtifactId, newVersion, decoderConfigurations,
161                     encoderConfigurations);
162         }
163
164         synchronized (this) {
165             droolsControllers.put(controllerId, controller);
166         }
167
168         final DroolsController controllerFinal = controller;
169
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));
175
176         return controller;
177     }
178
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()) {
184             try {
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);
192                     break;
193                 }
194             } catch (RuntimeException r) {
195                 logger.error("feature {} ({}) beforeInstance() of drools controller {}:{}:{} failed",
196                         feature.getName(), feature.getSequenceNumber(),
197                         newGroupId, newArtifactId, newVersion, r);
198             }
199         }
200         return controller;
201     }
202
203     protected List<DroolsControllerFeatureApi> getProviders() {
204         return DroolsControllerFeatureApiConstants.getProviders().getList();
205     }
206
207     /**
208      * find out decoder classes and filters.
209      *
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
213      *         filters
214      * @throws IllegalArgumentException invalid input data
215      */
216     protected List<TopicCoderFilterConfiguration> codersAndFilters(Properties properties,
217             List<? extends Topic> topicEntities) {
218
219         List<TopicCoderFilterConfiguration> topics2DecodedClasses2Filters = new ArrayList<>();
220
221         if (topicEntities == null || topicEntities.isEmpty()) {
222             return topics2DecodedClasses2Filters;
223         }
224
225         for (Topic topic : topicEntities) {
226
227             // 1. first the topic
228
229             String firstTopic = topic.getTopic();
230
231             String propertyTopicEntityPrefix = getPropertyTopicPrefix(topic) + firstTopic;
232
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
235
236             var customGsonCoder = getCustomCoder(properties, propertyTopicEntityPrefix);
237
238             // 3. second the list of classes associated with each topic
239
240             String eventClasses = properties
241                     .getProperty(propertyTopicEntityPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX);
242
243             if (eventClasses == null || eventClasses.isEmpty()) {
244                 logger.warn("There are no event classes for topic {}", firstTopic);
245                 continue;
246             }
247
248             List<PotentialCoderFilter> classes2Filters =
249                             getFilterExpressions(properties, propertyTopicEntityPrefix, eventClasses);
250
251             topics2DecodedClasses2Filters
252                     .add(new TopicCoderFilterConfiguration(firstTopic, classes2Filters, customGsonCoder));
253         }
254
255         return topics2DecodedClasses2Filters;
256     }
257
258     private String getPropertyTopicPrefix(Topic topic) {
259         boolean isSource = topic instanceof TopicSource;
260         var commInfra = topic.getTopicCommInfrastructure();
261         if (commInfra == CommInfrastructure.UEB) {
262             if (isSource) {
263                 return PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + ".";
264             } else {
265                 return PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + ".";
266             }
267         } else if (commInfra == CommInfrastructure.NOOP) {
268             if (isSource) {
269                 return PolicyEndPointProperties.PROPERTY_NOOP_SOURCE_TOPICS + ".";
270             } else {
271                 return PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS + ".";
272             }
273         } else if (commInfra == CommInfrastructure.KAFKA) {
274             if (isSource) {
275                 return PolicyEndPointProperties.PROPERTY_KAFKA_SOURCE_TOPICS + ".";
276             } else {
277                 return PolicyEndPointProperties.PROPERTY_KAFKA_SINK_TOPICS + ".";
278             }
279         } else {
280             throw new IllegalArgumentException("Invalid Communication Infrastructure: " + commInfra);
281         }
282     }
283
284     private CustomGsonCoder getCustomCoder(Properties properties, String propertyPrefix) {
285         String customGson = properties.getProperty(propertyPrefix
286                 + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_CUSTOM_MODEL_CODER_GSON_SUFFIX);
287
288         CustomGsonCoder customGsonCoder = null;
289         if (customGson != null && !customGson.isEmpty()) {
290             try {
291                 customGsonCoder = new CustomGsonCoder(customGson);
292             } catch (IllegalArgumentException e) {
293                 logger.warn("{}: cannot create custom-gson-coder {} because of {}", this, customGson,
294                         e.getMessage(), e);
295             }
296         }
297         return customGsonCoder;
298     }
299
300     private List<PotentialCoderFilter> getFilterExpressions(Properties properties, String propertyPrefix,
301                     @NonNull String eventClasses) {
302
303         List<PotentialCoderFilter> classes2Filters = new ArrayList<>();
304         for (String theClass : COMMA_SPACE_PAT.split(eventClasses)) {
305
306             // 4. for each coder class, get the filter expression
307
308             String filter = properties
309                     .getProperty(propertyPrefix
310                             + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX
311                             + "." + theClass + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_FILTER_SUFFIX);
312
313             var class2Filters = new PotentialCoderFilter(theClass, new JsonProtocolFilter(filter));
314             classes2Filters.add(class2Filters);
315         }
316
317         return classes2Filters;
318     }
319
320     @Override
321     public void destroy(DroolsController controller) {
322         unmanage(controller);
323         controller.halt();
324     }
325
326     @Override
327     public void destroy() {
328         List<DroolsController> controllers = this.inventory();
329         for (DroolsController controller : controllers) {
330             controller.halt();
331         }
332
333         synchronized (this) {
334             this.droolsControllers.clear();
335         }
336     }
337
338     /**
339      * unmanage the drools controller.
340      *
341      * @param controller the controller
342      */
343     protected void unmanage(DroolsController controller) {
344         if (controller == null) {
345             throw new IllegalArgumentException("No controller provided");
346         }
347
348         if (!controller.isBrained()) {
349             logger.info("Drools Controller is NOT OPERATIONAL - nothing to destroy");
350             return;
351         }
352
353         String controllerId = controller.getGroupId() + ":" + controller.getArtifactId();
354         synchronized (this) {
355             if (!this.droolsControllers.containsKey(controllerId)) {
356                 return;
357             }
358
359             droolsControllers.remove(controllerId);
360         }
361     }
362
363     @Override
364     public void shutdown(DroolsController controller) {
365         this.unmanage(controller);
366         controller.shutdown();
367     }
368
369     @Override
370     public void shutdown() {
371         List<DroolsController> controllers = this.inventory();
372         for (DroolsController controller : controllers) {
373             controller.shutdown();
374         }
375
376         synchronized (this) {
377             this.droolsControllers.clear();
378         }
379     }
380
381     @Override
382     public DroolsController get(String groupId, String artifactId, String version) {
383
384         if (groupId == null || artifactId == null || groupId.isEmpty() || artifactId.isEmpty()) {
385             throw new IllegalArgumentException("Missing maven coordinates: " + groupId + ":" + artifactId);
386         }
387
388         String controllerId = groupId + ":" + artifactId;
389
390         synchronized (this) {
391             if (this.droolsControllers.containsKey(controllerId)) {
392                 return droolsControllers.get(controllerId);
393             } else {
394                 throw new IllegalStateException("DroolController for " + controllerId + " not found");
395             }
396         }
397     }
398
399     @Override
400     public List<DroolsController> inventory() {
401         return new ArrayList<>(this.droolsControllers.values());
402     }
403
404     @Override
405     public String toString() {
406         return "IndexedDroolsControllerFactory [#droolsControllers=" + droolsControllers.size() + "]";
407     }
408
409 }