e5128bb5315586976fb76e327adaffc3bca45aff
[policy/drools-pdp.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019 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.Properties;
28 import org.onap.policy.common.endpoints.event.comm.Topic;
29 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
30 import org.onap.policy.common.endpoints.event.comm.TopicSink;
31 import org.onap.policy.common.endpoints.event.comm.TopicSource;
32 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
33 import org.onap.policy.drools.controller.internal.MavenDroolsController;
34 import org.onap.policy.drools.controller.internal.NullDroolsController;
35 import org.onap.policy.drools.properties.DroolsPropertyConstants;
36 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
37 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration;
38 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomGsonCoder;
39 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.PotentialCoderFilter;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Factory of Drools Controllers indexed by the Maven coordinates.
45  */
46 class IndexedDroolsControllerFactory implements DroolsControllerFactory {
47
48     /**
49      * logger.
50      */
51     private static Logger logger = LoggerFactory.getLogger(MavenDroolsController.class);
52
53     /**
54      * Policy Controller Name Index.
55      */
56     protected HashMap<String, DroolsController> droolsControllers = new HashMap<>();
57
58     /**
59      * Null Drools Controller.
60      */
61     protected NullDroolsController nullDroolsController = new NullDroolsController();
62
63     /**
64      * Constructs the object.
65      */
66     public IndexedDroolsControllerFactory() {
67
68         /* Add a NULL controller which will always be present in the hash */
69
70         DroolsController controller = new NullDroolsController();
71         String controllerId = controller.getGroupId() + ":" + controller.getArtifactId();
72
73         synchronized (this) {
74             droolsControllers.put(controllerId, controller);
75         }
76     }
77
78     @Override
79     public DroolsController build(Properties properties, List<? extends TopicSource> eventSources,
80             List<? extends TopicSink> eventSinks) throws LinkageError {
81
82         String groupId = properties.getProperty(DroolsPropertyConstants.RULES_GROUPID);
83         if (groupId == null || groupId.isEmpty()) {
84             groupId = DroolsControllerConstants.NO_GROUP_ID;
85         }
86
87         String artifactId = properties.getProperty(DroolsPropertyConstants.RULES_ARTIFACTID);
88         if (artifactId == null || artifactId.isEmpty()) {
89             artifactId = DroolsControllerConstants.NO_ARTIFACT_ID;
90         }
91
92         String version = properties.getProperty(DroolsPropertyConstants.RULES_VERSION);
93         if (version == null || version.isEmpty()) {
94             version = DroolsControllerConstants.NO_VERSION;
95         }
96
97         List<TopicCoderFilterConfiguration> topics2DecodedClasses2Filters = codersAndFilters(properties, eventSources);
98         List<TopicCoderFilterConfiguration> topics2EncodedClasses2Filters = codersAndFilters(properties, eventSinks);
99
100         return this.build(groupId, artifactId, version, topics2DecodedClasses2Filters, topics2EncodedClasses2Filters);
101     }
102
103     @Override
104     public DroolsController build(String newGroupId, String newArtifactId, String newVersion,
105             List<TopicCoderFilterConfiguration> decoderConfigurations,
106             List<TopicCoderFilterConfiguration> encoderConfigurations) throws LinkageError {
107
108         if (newGroupId == null || newGroupId.isEmpty()) {
109             throw new IllegalArgumentException("Missing maven group-id coordinate");
110         }
111
112         if (newArtifactId == null || newArtifactId.isEmpty()) {
113             throw new IllegalArgumentException("Missing maven artifact-id coordinate");
114         }
115
116         if (newVersion == null || newVersion.isEmpty()) {
117             throw new IllegalArgumentException("Missing maven version coordinate");
118         }
119
120         String controllerId = newGroupId + ":" + newArtifactId;
121         DroolsController controllerCopy = null;
122         synchronized (this) {
123             /*
124              * The Null Drools Controller for no maven coordinates is always here so when no
125              * coordinates present, this is the return point
126              *
127              * assert (controllerCopy instanceof NullDroolsController)
128              */
129             if (droolsControllers.containsKey(controllerId)) {
130                 controllerCopy = droolsControllers.get(controllerId);
131                 if (controllerCopy.getVersion().equalsIgnoreCase(newVersion)) {
132                     return controllerCopy;
133                 }
134             }
135         }
136
137         if (controllerCopy != null) {
138             /*
139              * a controller keyed by group id + artifact id exists but with different version =>
140              * version upgrade/downgrade
141              */
142
143             controllerCopy.updateToVersion(newGroupId, newArtifactId, newVersion, decoderConfigurations,
144                     encoderConfigurations);
145
146             return controllerCopy;
147         }
148
149         /* new drools controller */
150
151         DroolsController controller = new MavenDroolsController(newGroupId, newArtifactId, newVersion,
152                 decoderConfigurations, encoderConfigurations);
153
154         synchronized (this) {
155             droolsControllers.put(controllerId, controller);
156         }
157
158         return controller;
159     }
160
161     /**
162      * find out decoder classes and filters.
163      *
164      * @param properties properties with information about decoders
165      * @param topicEntities topic sources
166      * @return list of topics, each with associated decoder classes, each with a list of associated
167      *         filters
168      * @throws IllegalArgumentException invalid input data
169      */
170     protected List<TopicCoderFilterConfiguration> codersAndFilters(Properties properties,
171             List<? extends Topic> topicEntities) {
172
173         List<TopicCoderFilterConfiguration> topics2DecodedClasses2Filters = new ArrayList<>();
174
175         if (topicEntities == null || topicEntities.isEmpty()) {
176             return topics2DecodedClasses2Filters;
177         }
178
179         for (Topic topic : topicEntities) {
180
181             // 1. first the topic
182
183             String firstTopic = topic.getTopic();
184
185             String propertyTopicEntityPrefix = getPropertyTopicPrefix(topic) + firstTopic;
186
187             // 2. check if there is a custom decoder for this topic that the user prefers to use
188             // instead of the ones provided in the platform
189
190             CustomGsonCoder customGsonCoder = getCustomCoder(properties, propertyTopicEntityPrefix);
191
192             // 3. second the list of classes associated with each topic
193
194             String eventClasses = properties
195                     .getProperty(propertyTopicEntityPrefix + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX);
196
197             if (eventClasses == null || eventClasses.isEmpty()) {
198                 logger.warn("There are no event classes for topic {}", firstTopic);
199                 continue;
200             }
201
202             List<PotentialCoderFilter> classes2Filters =
203                             getFilterExpressions(properties, propertyTopicEntityPrefix, eventClasses);
204
205             TopicCoderFilterConfiguration topic2Classes2Filters =
206                     new TopicCoderFilterConfiguration(firstTopic, classes2Filters, customGsonCoder);
207             topics2DecodedClasses2Filters.add(topic2Classes2Filters);
208         }
209
210         return topics2DecodedClasses2Filters;
211     }
212
213     private String getPropertyTopicPrefix(Topic topic) {
214         boolean isSource = topic instanceof TopicSource;
215         CommInfrastructure commInfra = topic.getTopicCommInfrastructure();
216         if (commInfra == CommInfrastructure.UEB) {
217             if (isSource) {
218                 return PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + ".";
219             } else {
220                 return PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + ".";
221             }
222         } else if (commInfra == CommInfrastructure.DMAAP) {
223             if (isSource) {
224                 return PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + ".";
225             } else {
226                 return PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + ".";
227             }
228         } else if (commInfra == CommInfrastructure.NOOP) {
229             if (isSource) {
230                 return PolicyEndPointProperties.PROPERTY_NOOP_SOURCE_TOPICS + ".";
231             } else {
232                 return PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS + ".";
233             }
234         } else {
235             throw new IllegalArgumentException("Invalid Communication Infrastructure: " + commInfra);
236         }
237     }
238
239     private CustomGsonCoder getCustomCoder(Properties properties, String propertyPrefix) {
240         String customGson = properties.getProperty(propertyPrefix
241                 + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_CUSTOM_MODEL_CODER_GSON_SUFFIX);
242
243         CustomGsonCoder customGsonCoder = null;
244         if (customGson != null && !customGson.isEmpty()) {
245             try {
246                 customGsonCoder = new CustomGsonCoder(customGson);
247             } catch (IllegalArgumentException e) {
248                 logger.warn("{}: cannot create custom-gson-coder {} because of {}", this, customGson,
249                         e.getMessage(), e);
250             }
251         }
252         return customGsonCoder;
253     }
254
255     private List<PotentialCoderFilter> getFilterExpressions(Properties properties, String propertyPrefix,
256                     String eventClasses) {
257
258         List<PotentialCoderFilter> classes2Filters = new ArrayList<>();
259
260         List<String> topicClasses = new ArrayList<>(Arrays.asList(eventClasses.split("\\s*,\\s*")));
261
262         for (String theClass : topicClasses) {
263
264             // 4. for each coder class, get the filter expression
265
266             String filter = properties
267                     .getProperty(propertyPrefix
268                             + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX
269                             + "." + theClass + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_FILTER_SUFFIX);
270
271             JsonProtocolFilter protocolFilter = new JsonProtocolFilter(filter);
272             PotentialCoderFilter class2Filters = new PotentialCoderFilter(theClass, protocolFilter);
273             classes2Filters.add(class2Filters);
274         }
275
276         return classes2Filters;
277     }
278
279     @Override
280     public void destroy(DroolsController controller) {
281         unmanage(controller);
282         controller.halt();
283     }
284
285     @Override
286     public void destroy() {
287         List<DroolsController> controllers = this.inventory();
288         for (DroolsController controller : controllers) {
289             controller.halt();
290         }
291
292         synchronized (this) {
293             this.droolsControllers.clear();
294         }
295     }
296
297     /**
298      * unmanage the drools controller.
299      *
300      * @param controller the controller
301      */
302     protected void unmanage(DroolsController controller) {
303         if (controller == null) {
304             throw new IllegalArgumentException("No controller provided");
305         }
306
307         if (!controller.isBrained()) {
308             logger.info("Drools Controller is NOT OPERATIONAL - nothing to destroy");
309             return;
310         }
311
312         String controllerId = controller.getGroupId() + ":" + controller.getArtifactId();
313         synchronized (this) {
314             if (!this.droolsControllers.containsKey(controllerId)) {
315                 return;
316             }
317
318             droolsControllers.remove(controllerId);
319         }
320     }
321
322     @Override
323     public void shutdown(DroolsController controller) {
324         this.unmanage(controller);
325         controller.shutdown();
326     }
327
328     @Override
329     public void shutdown() {
330         List<DroolsController> controllers = this.inventory();
331         for (DroolsController controller : controllers) {
332             controller.shutdown();
333         }
334
335         synchronized (this) {
336             this.droolsControllers.clear();
337         }
338     }
339
340     @Override
341     public DroolsController get(String groupId, String artifactId, String version) {
342
343         if (groupId == null || artifactId == null || groupId.isEmpty() || artifactId.isEmpty()) {
344             throw new IllegalArgumentException("Missing maven coordinates: " + groupId + ":" + artifactId);
345         }
346
347         String controllerId = groupId + ":" + artifactId;
348
349         synchronized (this) {
350             if (this.droolsControllers.containsKey(controllerId)) {
351                 return droolsControllers.get(controllerId);
352             } else {
353                 throw new IllegalStateException("DroolController for " + controllerId + " not found");
354             }
355         }
356     }
357
358     @Override
359     public List<DroolsController> inventory() {
360         return new ArrayList<>(this.droolsControllers.values());
361     }
362
363     @Override
364     public String toString() {
365         StringBuilder builder = new StringBuilder();
366         builder.append("IndexedDroolsControllerFactory [#droolsControllers=").append(droolsControllers.size())
367                 .append("]");
368         return builder.toString();
369     }
370
371 }