7f28f9bbd41824121122438e2f08f2fb74825245
[policy/drools-pdp.git] /
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.NOOP) {
262             if (isSource) {
263                 return PolicyEndPointProperties.PROPERTY_NOOP_SOURCE_TOPICS + ".";
264             } else {
265                 return PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS + ".";
266             }
267         } else if (commInfra == CommInfrastructure.KAFKA) {
268             if (isSource) {
269                 return PolicyEndPointProperties.PROPERTY_KAFKA_SOURCE_TOPICS + ".";
270             } else {
271                 return PolicyEndPointProperties.PROPERTY_KAFKA_SINK_TOPICS + ".";
272             }
273         } else {
274             throw new IllegalArgumentException("Invalid Communication Infrastructure: " + commInfra);
275         }
276     }
277
278     private CustomGsonCoder getCustomCoder(Properties properties, String propertyPrefix) {
279         String customGson = properties.getProperty(propertyPrefix
280                 + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_CUSTOM_MODEL_CODER_GSON_SUFFIX);
281
282         CustomGsonCoder customGsonCoder = null;
283         if (customGson != null && !customGson.isEmpty()) {
284             try {
285                 customGsonCoder = new CustomGsonCoder(customGson);
286             } catch (IllegalArgumentException e) {
287                 logger.warn("{}: cannot create custom-gson-coder {} because of {}", this, customGson,
288                         e.getMessage(), e);
289             }
290         }
291         return customGsonCoder;
292     }
293
294     private List<PotentialCoderFilter> getFilterExpressions(Properties properties, String propertyPrefix,
295                     @NonNull String eventClasses) {
296
297         List<PotentialCoderFilter> classes2Filters = new ArrayList<>();
298         for (String theClass : COMMA_SPACE_PAT.split(eventClasses)) {
299
300             // 4. for each coder class, get the filter expression
301
302             String filter = properties
303                     .getProperty(propertyPrefix
304                             + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX
305                             + "." + theClass + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_FILTER_SUFFIX);
306
307             var class2Filters = new PotentialCoderFilter(theClass, new JsonProtocolFilter(filter));
308             classes2Filters.add(class2Filters);
309         }
310
311         return classes2Filters;
312     }
313
314     @Override
315     public void destroy(DroolsController controller) {
316         unmanage(controller);
317         controller.halt();
318     }
319
320     @Override
321     public void destroy() {
322         List<DroolsController> controllers = this.inventory();
323         for (DroolsController controller : controllers) {
324             controller.halt();
325         }
326
327         synchronized (this) {
328             this.droolsControllers.clear();
329         }
330     }
331
332     /**
333      * unmanage the drools controller.
334      *
335      * @param controller the controller
336      */
337     protected void unmanage(DroolsController controller) {
338         if (controller == null) {
339             throw new IllegalArgumentException("No controller provided");
340         }
341
342         if (!controller.isBrained()) {
343             logger.info("Drools Controller is NOT OPERATIONAL - nothing to destroy");
344             return;
345         }
346
347         String controllerId = controller.getGroupId() + ":" + controller.getArtifactId();
348         synchronized (this) {
349             if (!this.droolsControllers.containsKey(controllerId)) {
350                 return;
351             }
352
353             droolsControllers.remove(controllerId);
354         }
355     }
356
357     @Override
358     public void shutdown(DroolsController controller) {
359         this.unmanage(controller);
360         controller.shutdown();
361     }
362
363     @Override
364     public void shutdown() {
365         List<DroolsController> controllers = this.inventory();
366         for (DroolsController controller : controllers) {
367             controller.shutdown();
368         }
369
370         synchronized (this) {
371             this.droolsControllers.clear();
372         }
373     }
374
375     @Override
376     public DroolsController get(String groupId, String artifactId, String version) {
377
378         if (groupId == null || artifactId == null || groupId.isEmpty() || artifactId.isEmpty()) {
379             throw new IllegalArgumentException("Missing maven coordinates: " + groupId + ":" + artifactId);
380         }
381
382         String controllerId = groupId + ":" + artifactId;
383
384         synchronized (this) {
385             if (this.droolsControllers.containsKey(controllerId)) {
386                 return droolsControllers.get(controllerId);
387             } else {
388                 throw new IllegalStateException("DroolController for " + controllerId + " not found");
389             }
390         }
391     }
392
393     @Override
394     public List<DroolsController> inventory() {
395         return new ArrayList<>(this.droolsControllers.values());
396     }
397
398     @Override
399     public String toString() {
400         return "IndexedDroolsControllerFactory [#droolsControllers=" + droolsControllers.size() + "]";
401     }
402
403 }