8255c027458bacd66cf143e190ca506343091142
[policy/drools-pdp.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 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.lifecycle;
22
23 import com.fasterxml.jackson.annotation.JsonIgnore;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Properties;
28 import java.util.stream.Collectors;
29 import lombok.Getter;
30 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
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.gson.annotation.GsonJsonIgnore;
34 import org.onap.policy.common.utils.coder.CoderException;
35 import org.onap.policy.drools.domain.models.controller.ControllerCustomSerialization;
36 import org.onap.policy.drools.domain.models.controller.ControllerEvent;
37 import org.onap.policy.drools.domain.models.controller.ControllerPolicy;
38 import org.onap.policy.drools.domain.models.controller.ControllerProperties;
39 import org.onap.policy.drools.domain.models.controller.ControllerSinkTopic;
40 import org.onap.policy.drools.domain.models.controller.ControllerSourceTopic;
41 import org.onap.policy.drools.properties.DroolsPropertyConstants;
42 import org.onap.policy.drools.system.PolicyController;
43 import org.onap.policy.drools.system.PolicyControllerConstants;
44 import org.onap.policy.drools.system.PolicyEngineConstants;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 public class PolicyTypeNativeDroolsController implements PolicyTypeController {
51     private static final Logger logger = LoggerFactory.getLogger(PolicyTypeNativeDroolsController.class);
52
53     @Getter
54     protected final ToscaPolicyTypeIdentifier policyType;
55
56     @GsonJsonIgnore
57     @JsonIgnore
58     protected final transient LifecycleFsm fsm;
59
60     public PolicyTypeNativeDroolsController(LifecycleFsm fsm, ToscaPolicyTypeIdentifier policyType) {
61         this.policyType = policyType;
62         this.fsm = fsm;
63     }
64
65     @Override
66     public boolean deploy(ToscaPolicy policy) {
67         Properties controllerProps = new Properties();
68         ControllerPolicy controllerPolicy = toDomainPolicy(policy);
69         if (controllerPolicy == null) {
70             return false;
71         }
72
73         ControllerProperties controllerConfig = controllerPolicy.getProperties();
74
75         boolean success =
76             configControllerName(controllerConfig, controllerProps)
77             && configControllerSources(controllerConfig, controllerProps)
78             && configControllerSinks(controllerConfig, controllerProps)
79             && configControllerCustom(controllerConfig, controllerProps);
80
81         if (!success) {
82             return false;
83         }
84
85         PolicyController controller;
86         try {
87             controller = PolicyEngineConstants.getManager()
88                                  .createPolicyController(controllerConfig.getControllerName(), controllerProps);
89         } catch (RuntimeException e) {
90             logger.warn("failed deploy (cannot create controller) for policy: {}", policy);
91             return false;
92         }
93
94         return controller != null;
95     }
96
97     @Override
98     public boolean undeploy(ToscaPolicy policy) {
99         try {
100             ControllerPolicy nativePolicy = fsm.getDomainMaker().convertTo(policy, ControllerPolicy.class);
101             PolicyEngineConstants.getManager()
102                     .removePolicyController(nativePolicy.getProperties().getControllerName());
103             return true;
104         } catch (RuntimeException | CoderException e) {
105             logger.warn("failed undeploy of policy: {}", policy);
106             return false;
107         }
108     }
109
110     private ControllerPolicy toDomainPolicy(ToscaPolicy policy) {
111         ControllerPolicy nativePolicy = null;
112         try {
113             nativePolicy = fsm.getDomainMaker().convertTo(policy, ControllerPolicy.class);
114             ControllerProperties config = nativePolicy.getProperties();
115
116             /* check for duplicates */
117
118             if (isDups(sourceTopics(config.getSourceTopics()))
119                         || isDups(sinkTopics(config.getSinkTopics()))) {
120                 logger.warn("there are duplicated topics in policy {}", policy);
121                 return null;
122             }
123
124             /* check for non-existance of the controller - throws IAE if there's not */
125
126             PolicyControllerConstants.getFactory().get(nativePolicy.getProperties().getControllerName());
127
128         } catch (CoderException e) {
129             logger.warn("failed deploy of policy (invalid): {}", policy);
130             return null;
131         } catch (IllegalArgumentException e) {
132             // this is OK
133             logger.trace("proceeding with the deploy of native controller policy: {}", policy);
134         }
135
136         return nativePolicy;
137     }
138
139     private boolean configControllerName(ControllerProperties controllerConfig, Properties controllerProps)  {
140         controllerProps
141                 .setProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, controllerConfig.getControllerName());
142         return true;
143     }
144
145     private boolean configControllerSources(ControllerProperties controllerConfig, Properties controllerProps) {
146         if (controllerConfig.getSourceTopics() == null) {
147             return true;
148         }
149
150         for (ControllerSourceTopic configSourceTopic : controllerConfig.getSourceTopics()) {
151             List<TopicSource> sources =
152                     TopicEndpointManager.getManager().getTopicSources(List.of(configSourceTopic.getTopicName()));
153             if (sources.size() != 1) {
154                 logger.warn("Topic {} is not present or ambigous {}", configSourceTopic.getTopicName(), sources);
155                 return false;
156             }
157
158             configSourceTopic(sources.get(0), configSourceTopic, controllerProps);
159         }
160         return true;
161     }
162
163     private void configSourceTopic(TopicSource topic, ControllerSourceTopic configTopic, Properties controllerProps) {
164         String configCommPrefix = topic.getTopicCommInfrastructure().name().toLowerCase() + ".source";
165         configTopic(configCommPrefix, topic.getTopic(), configTopic.getEvents(), controllerProps);
166     }
167
168     private boolean configControllerSinks(ControllerProperties controllerConfig, Properties controllerProps) {
169         if (controllerConfig.getSinkTopics() == null) {
170             return true;
171         }
172
173         for (ControllerSinkTopic configSinkTopic : controllerConfig.getSinkTopics()) {
174             List<TopicSink> sinks =
175                     TopicEndpointManager.getManager().getTopicSinks(List.of(configSinkTopic.getTopicName()));
176             if (sinks.size() != 1) {
177                 logger.warn("Topic {} is not present or ambigous {}", configSinkTopic.getTopicName(), sinks);
178                 return false;
179             }
180
181             configSinkTopic(sinks.get(0), configSinkTopic, controllerProps);
182         }
183         return true;
184     }
185
186     private void configSinkTopic(TopicSink topic, ControllerSinkTopic configTopic, Properties controllerProps) {
187         String configCommPrefix = topic.getTopicCommInfrastructure().name().toLowerCase() + ".sink";
188         configTopic(configCommPrefix, topic.getTopic(), configTopic.getEvents(), controllerProps);
189     }
190
191     private void configTopic(
192             String configCommPrefix, String topicName, List<ControllerEvent> events, Properties controllerProps) {
193         String configTopicPrefix = configCommPrefix + "." + topicName;
194         configTopics(configCommPrefix, topicName, controllerProps);
195         for (ControllerEvent configEvent : events) {
196             configEvent(configTopicPrefix, configEvent, controllerProps);
197         }
198     }
199
200     private void configTopics(String propPrefix, String topicName, Properties controllerProps) {
201         String topicsPropKey = propPrefix + ".topics";
202         configTopicItemList(topicsPropKey, topicName, controllerProps);
203     }
204
205     private void configEvent(String propPrefix, ControllerEvent configEvent, Properties controllerProps) {
206         String eventPropPrefix = propPrefix + ".events";
207         controllerProps.setProperty(eventPropPrefix, configEvent.getEventClass());
208         if (configEvent.getEventFilter() != null) {
209             controllerProps.setProperty(
210                 eventPropPrefix + "." + configEvent.getEventClass() + ".filter", configEvent.getEventFilter());
211         }
212         if (configEvent.getCustomSerialization() != null) {
213             configSerialization(eventPropPrefix, configEvent.getCustomSerialization(), controllerProps);
214         }
215         configTopicItemList(eventPropPrefix, configEvent.getEventClass(), controllerProps);
216     }
217
218     private void configTopicItemList(String itemPrefix, String item, Properties controllerProps) {
219         if (controllerProps.getProperty(itemPrefix) == null) {
220             controllerProps.setProperty(itemPrefix, item);
221         } else {
222             controllerProps.setProperty(itemPrefix, "," + item);
223         }
224     }
225
226     private void configSerialization(
227             String propPrefix, ControllerCustomSerialization configCustom, Properties controllerProps) {
228         String customPropPrefix = propPrefix + ".custom.gson";
229         controllerProps.setProperty(
230                 customPropPrefix, configCustom.getCustomSerializerClass() + "," + configCustom.getJsonParser());
231     }
232
233     private boolean configControllerCustom(ControllerProperties controllerConfig, Properties controllerProps) {
234         Map<String, String> configCustom = controllerConfig.getCustomConfig();
235         if (configCustom == null || configCustom.isEmpty()) {
236             return true;
237         }
238
239         controllerProps.putAll(configCustom);
240         return true;
241     }
242
243     private <T> boolean isDups(List<T> items) {
244         return items.size() != items.stream().distinct().count();
245     }
246
247     private List<String> sourceTopics(List<ControllerSourceTopic> sourceTopics) {
248         if (sourceTopics == null) {
249             return Collections.EMPTY_LIST;
250         }
251
252         return sourceTopics.stream()
253                        .map(ControllerSourceTopic::getTopicName)
254                        .collect(Collectors.toList());
255     }
256
257     private List<String> sinkTopics(List<ControllerSinkTopic> sinkTopics) {
258         if (sinkTopics == null) {
259             return Collections.EMPTY_LIST;
260         }
261
262         return sinkTopics.stream()
263                        .map(ControllerSinkTopic::getTopicName)
264                        .collect(Collectors.toList());
265     }
266
267 }