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