e74b289508c125a49a1bfc2a3b5f7d3de0f16f0c
[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 =
88                 PolicyEngineConstants.getManager()
89                     .createPolicyController(controllerConfig.getControllerName(), controllerProps);
90         } catch (RuntimeException e) {
91             logger.warn("failed deploy (cannot create controller) for policy: {}", policy, e);
92             return false;
93         }
94
95         try {
96             controller.start();
97         } catch (RuntimeException e) {
98             logger.warn("failed deploy (cannot start ontroller) for policy: {}", policy, e);
99             PolicyEngineConstants.getManager().removePolicyController(controller);
100             return false;
101         }
102
103         return true;
104     }
105
106     @Override
107     public boolean undeploy(ToscaPolicy policy) {
108         try {
109             ControllerPolicy nativePolicy = fsm.getDomainMaker().convertTo(policy, ControllerPolicy.class);
110             PolicyEngineConstants.getManager()
111                     .removePolicyController(nativePolicy.getProperties().getControllerName());
112             return true;
113         } catch (RuntimeException | CoderException e) {
114             logger.warn("failed undeploy of policy: {}", policy);
115             return false;
116         }
117     }
118
119     private ControllerPolicy toDomainPolicy(ToscaPolicy policy) {
120         ControllerPolicy nativePolicy = null;
121         try {
122             nativePolicy = fsm.getDomainMaker().convertTo(policy, ControllerPolicy.class);
123             ControllerProperties config = nativePolicy.getProperties();
124
125             /* check for duplicates */
126
127             if (isDups(sourceTopics(config.getSourceTopics()))
128                         || isDups(sinkTopics(config.getSinkTopics()))) {
129                 logger.warn("there are duplicated topics in policy {}", policy);
130                 return null;
131             }
132
133             /* check for non-existance of the controller - throws IAE if there's not */
134
135             PolicyControllerConstants.getFactory().get(nativePolicy.getProperties().getControllerName());
136
137         } catch (CoderException e) {
138             logger.warn("failed deploy of policy (invalid): {}", policy);
139             return null;
140         } catch (IllegalArgumentException e) {
141             // this is OK
142             logger.trace("proceeding with the deploy of native controller policy: {}", policy);
143         }
144
145         return nativePolicy;
146     }
147
148     private boolean configControllerName(ControllerProperties controllerConfig, Properties controllerProps)  {
149         controllerProps
150                 .setProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, controllerConfig.getControllerName());
151         return true;
152     }
153
154     private boolean configControllerSources(ControllerProperties controllerConfig, Properties controllerProps) {
155         if (controllerConfig.getSourceTopics() == null) {
156             return true;
157         }
158
159         for (ControllerSourceTopic configSourceTopic : controllerConfig.getSourceTopics()) {
160             List<TopicSource> sources =
161                     TopicEndpointManager.getManager().getTopicSources(List.of(configSourceTopic.getTopicName()));
162             if (sources.size() != 1) {
163                 logger.warn("Topic {} is not present or ambigous {}", configSourceTopic.getTopicName(), sources);
164                 return false;
165             }
166
167             configSourceTopic(sources.get(0), configSourceTopic, controllerProps);
168         }
169         return true;
170     }
171
172     private void configSourceTopic(TopicSource topic, ControllerSourceTopic configTopic, Properties controllerProps) {
173         String configCommPrefix = topic.getTopicCommInfrastructure().name().toLowerCase() + ".source";
174         configTopic(configCommPrefix, topic.getTopic(), configTopic.getEvents(), controllerProps);
175     }
176
177     private boolean configControllerSinks(ControllerProperties controllerConfig, Properties controllerProps) {
178         if (controllerConfig.getSinkTopics() == null) {
179             return true;
180         }
181
182         for (ControllerSinkTopic configSinkTopic : controllerConfig.getSinkTopics()) {
183             List<TopicSink> sinks =
184                     TopicEndpointManager.getManager().getTopicSinks(List.of(configSinkTopic.getTopicName()));
185             if (sinks.size() != 1) {
186                 logger.warn("Topic {} is not present or ambigous {}", configSinkTopic.getTopicName(), sinks);
187                 return false;
188             }
189
190             configSinkTopic(sinks.get(0), configSinkTopic, controllerProps);
191         }
192         return true;
193     }
194
195     private void configSinkTopic(TopicSink topic, ControllerSinkTopic configTopic, Properties controllerProps) {
196         String configCommPrefix = topic.getTopicCommInfrastructure().name().toLowerCase() + ".sink";
197         configTopic(configCommPrefix, topic.getTopic(), configTopic.getEvents(), controllerProps);
198     }
199
200     private void configTopic(
201             String configCommPrefix, String topicName, List<ControllerEvent> events, Properties controllerProps) {
202         String configTopicPrefix = configCommPrefix + "." + topicName;
203         configTopics(configCommPrefix, topicName, controllerProps);
204         for (ControllerEvent configEvent : events) {
205             configEvent(configTopicPrefix, configEvent, controllerProps);
206         }
207     }
208
209     private void configTopics(String propPrefix, String topicName, Properties controllerProps) {
210         String topicsPropKey = propPrefix + ".topics";
211         configTopicItemList(topicsPropKey, topicName, controllerProps);
212     }
213
214     private void configEvent(String propPrefix, ControllerEvent configEvent, Properties controllerProps) {
215         String eventPropPrefix = propPrefix + ".events";
216         controllerProps.setProperty(eventPropPrefix, configEvent.getEventClass());
217         if (configEvent.getEventFilter() != null) {
218             controllerProps.setProperty(
219                 eventPropPrefix + "." + configEvent.getEventClass() + ".filter", configEvent.getEventFilter());
220         }
221         if (configEvent.getCustomSerialization() != null) {
222             configSerialization(eventPropPrefix, configEvent.getCustomSerialization(), controllerProps);
223         }
224         configTopicItemList(eventPropPrefix, configEvent.getEventClass(), controllerProps);
225     }
226
227     private void configTopicItemList(String itemPrefix, String item, Properties controllerProps) {
228         if (controllerProps.getProperty(itemPrefix) == null) {
229             controllerProps.setProperty(itemPrefix, item);
230         } else {
231             controllerProps.setProperty(itemPrefix, "," + item);
232         }
233     }
234
235     private void configSerialization(
236             String propPrefix, ControllerCustomSerialization configCustom, Properties controllerProps) {
237         String customPropPrefix = propPrefix + ".custom.gson";
238         controllerProps.setProperty(
239                 customPropPrefix, configCustom.getCustomSerializerClass() + "," + configCustom.getJsonParser());
240     }
241
242     private boolean configControllerCustom(ControllerProperties controllerConfig, Properties controllerProps) {
243         Map<String, String> configCustom = controllerConfig.getCustomConfig();
244         if (configCustom == null || configCustom.isEmpty()) {
245             return true;
246         }
247
248         controllerProps.putAll(configCustom);
249         return true;
250     }
251
252     private <T> boolean isDups(List<T> items) {
253         return items.size() != items.stream().distinct().count();
254     }
255
256     private List<String> sourceTopics(List<ControllerSourceTopic> sourceTopics) {
257         if (sourceTopics == null) {
258             return Collections.EMPTY_LIST;
259         }
260
261         return sourceTopics.stream()
262                        .map(ControllerSourceTopic::getTopicName)
263                        .collect(Collectors.toList());
264     }
265
266     private List<String> sinkTopics(List<ControllerSinkTopic> sinkTopics) {
267         if (sinkTopics == null) {
268             return Collections.EMPTY_LIST;
269         }
270
271         return sinkTopics.stream()
272                        .map(ControllerSinkTopic::getTopicName)
273                        .collect(Collectors.toList());
274     }
275
276 }