2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018-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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.drools.pooling;
23 import java.util.List;
24 import java.util.Properties;
25 import java.util.UUID;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.CountDownLatch;
28 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
29 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
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.utils.properties.SpecProperties;
33 import org.onap.policy.common.utils.properties.exception.PropertyException;
34 import org.onap.policy.drools.controller.DroolsController;
35 import org.onap.policy.drools.features.DroolsControllerFeatureApi;
36 import org.onap.policy.drools.features.PolicyControllerFeatureApi;
37 import org.onap.policy.drools.features.PolicyEngineFeatureApi;
38 import org.onap.policy.drools.persistence.SystemPersistenceConstants;
39 import org.onap.policy.drools.system.PolicyController;
40 import org.onap.policy.drools.system.PolicyControllerConstants;
41 import org.onap.policy.drools.system.PolicyEngine;
42 import org.onap.policy.drools.util.FeatureEnabledChecker;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * Controller/session pooling. Multiple hosts may be launched, all servicing the same
48 * controllers/sessions. When this feature is enabled, the requests are divided across the different
49 * hosts, instead of all running on a single, active host.
51 * <p>With each controller, there is an
52 * associated DMaaP topic that is used for internal communication between the different hosts
53 * serving the controller.
55 public class PoolingFeature implements PolicyEngineFeatureApi, PolicyControllerFeatureApi, DroolsControllerFeatureApi {
57 private static final Logger logger = LoggerFactory.getLogger(PoolingFeature.class);
62 private final String host;
65 * Entire set of feature properties, including those specific to various controllers.
67 private Properties featProps = null;
70 * Maps a controller name to its associated manager.
72 private final ConcurrentHashMap<String, PoolingManagerImpl> ctlr2pool = new ConcurrentHashMap<>(107);
75 * Decremented each time a manager enters the Active state. Used by junit tests.
77 private final CountDownLatch activeLatch = new CountDownLatch(1);
80 * Topic names passed to beforeOffer(), which are saved for when the beforeInsert() is
81 * called later. As multiple threads can be active within the methods at the same
82 * time, we must keep this in thread local storage.
84 private ThreadLocal<String> offerTopics = new ThreadLocal<>();
89 public PoolingFeature() {
92 this.host = UUID.randomUUID().toString();
95 public String getHost() {
102 * @return a latch that will be decremented when a manager enters the active state
104 protected CountDownLatch getActiveLatch() {
109 public int getSequenceNumber() {
114 public boolean beforeStart(PolicyEngine engine) {
115 logger.info("initializing {}", PoolingProperties.FEATURE_NAME);
116 featProps = getProperties(PoolingProperties.FEATURE_NAME);
118 // remove any generic pooling topic - always use controller-specific property
119 featProps.remove(PoolingProperties.POOLING_TOPIC);
121 initTopicSources(featProps);
122 initTopicSinks(featProps);
128 public boolean beforeStart(PolicyController controller) {
129 return doManager(controller, mgr -> {
136 * Adds the controller and a new pooling manager to {@link #ctlr2pool}.
138 * @throws PoolingFeatureRtException if an error occurs
141 public boolean afterCreate(PolicyController controller) {
143 if (featProps == null) {
144 logger.error("pooling feature properties have not been loaded");
145 throw new PoolingFeatureRtException(new IllegalStateException("missing pooling feature properties"));
148 String name = controller.getName();
150 SpecProperties specProps = new SpecProperties(PoolingProperties.PREFIX, name, featProps);
152 if (FeatureEnabledChecker.isFeatureEnabled(specProps, PoolingProperties.FEATURE_ENABLED)) {
154 // get & validate the properties
155 PoolingProperties props = new PoolingProperties(name, featProps);
157 logger.info("pooling enabled for {}", name);
158 ctlr2pool.computeIfAbsent(name, xxx -> makeManager(host, controller, props, activeLatch));
160 } catch (PropertyException e) {
161 logger.error("pooling disabled due to exception for {}", name);
162 throw new PoolingFeatureRtException(e);
166 logger.info("pooling disabled for {}", name);
174 public boolean afterStart(PolicyController controller) {
175 return doManager(controller, mgr -> {
182 public boolean beforeStop(PolicyController controller) {
183 return doManager(controller, mgr -> {
190 public boolean afterStop(PolicyController controller) {
191 return doManager(controller, mgr -> {
198 public boolean afterShutdown(PolicyController controller) {
199 return commonShutdown(controller);
203 public boolean afterHalt(PolicyController controller) {
204 return commonShutdown(controller);
207 private boolean commonShutdown(PolicyController controller) {
208 deleteManager(controller);
213 public boolean beforeLock(PolicyController controller) {
214 return doManager(controller, mgr -> {
221 public boolean afterUnlock(PolicyController controller) {
222 return doManager(controller, mgr -> {
229 public boolean beforeOffer(PolicyController controller, CommInfrastructure protocol, String topic2, String event) {
231 * As this is invoked a lot, we'll directly call the manager's method instead of using the
232 * functional interface via doManager().
234 PoolingManagerImpl mgr = ctlr2pool.get(controller.getName());
239 if (mgr.beforeOffer(topic2, event)) {
243 offerTopics.set(topic2);
248 public boolean beforeInsert(DroolsController droolsController, Object fact) {
250 String topic = offerTopics.get();
252 logger.warn("missing arguments for feature-pooling-dmaap in beforeInsert");
256 PolicyController controller;
258 controller = getController(droolsController);
260 } catch (IllegalArgumentException | IllegalStateException e) {
261 logger.warn("cannot get controller for {} {}", droolsController.getGroupId(),
262 droolsController.getArtifactId(), e);
267 if (controller == null) {
268 logger.warn("cannot determine controller for {} {}", droolsController.getGroupId(),
269 droolsController.getArtifactId());
274 * As this is invoked a lot, we'll directly call the manager's method instead of using the
275 * functional interface via doManager().
277 PoolingManagerImpl mgr = ctlr2pool.get(controller.getName());
282 return mgr.beforeInsert(topic, fact);
286 public boolean afterOffer(PolicyController controller, CommInfrastructure protocol, String topic, String event,
289 // clear any stored arguments
290 offerTopics.remove();
296 * Executes a function using the manager associated with the controller. Catches any exceptions
297 * from the function and re-throws it as a runtime exception.
299 * @param controller controller
300 * @param func function to be executed
301 * @return {@code true} if the function handled the request, {@code false} otherwise
302 * @throws PoolingFeatureRtException if an error occurs
304 private boolean doManager(PolicyController controller, MgrFunc func) {
305 PoolingManagerImpl mgr = ctlr2pool.get(controller.getName());
311 return func.apply(mgr);
313 } catch (PoolingFeatureException e) {
314 throw new PoolingFeatureRtException(e);
319 * Deletes the manager associated with a controller.
321 * @param controller controller
322 * @throws PoolingFeatureRtException if an error occurs
324 private void deleteManager(PolicyController controller) {
326 String name = controller.getName();
327 logger.info("remove feature-pool-dmaap manager for {}", name);
329 ctlr2pool.remove(name);
333 * Function that operates on a manager.
336 private static interface MgrFunc {
342 * @return {@code true} if the request was handled by the manager, {@code false} otherwise
343 * @throws PoolingFeatureException feature exception
345 boolean apply(PoolingManagerImpl mgr) throws PoolingFeatureException;
349 * The remaining methods may be overridden by junit tests.
355 * @param featName feature name
356 * @return the properties for the specified feature
358 protected Properties getProperties(String featName) {
359 return SystemPersistenceConstants.getManager().getProperties(featName);
363 * Makes a pooling manager for a controller.
365 * @param host name/uuid of this host
366 * @param controller controller
367 * @param props properties to use to configure the manager
368 * @param activeLatch decremented when the manager goes Active
369 * @return a new pooling manager
371 protected PoolingManagerImpl makeManager(String host, PolicyController controller, PoolingProperties props,
372 CountDownLatch activeLatch) {
373 return new PoolingManagerImpl(host, controller, props, activeLatch);
377 * Gets the policy controller associated with a drools controller.
379 * @param droolsController drools controller
380 * @return the policy controller associated with a drools controller
382 protected PolicyController getController(DroolsController droolsController) {
383 return PolicyControllerConstants.getFactory().get(droolsController);
387 * Initializes the topic sources.
389 * @param props properties used to configure the topics
390 * @return the topic sources
392 protected List<TopicSource> initTopicSources(Properties props) {
393 return TopicEndpointManager.getManager().addTopicSources(props);
397 * Initializes the topic sinks.
399 * @param props properties used to configure the topics
400 * @return the topic sinks
402 protected List<TopicSink> initTopicSinks(Properties props) {
403 return TopicEndpointManager.getManager().addTopicSinks(props);