2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-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
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.system.internal;
23 import com.fasterxml.jackson.annotation.JsonIgnore;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Properties;
29 import java.util.stream.Collectors;
30 import org.onap.policy.common.endpoints.event.comm.Topic;
31 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
32 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
33 import org.onap.policy.common.endpoints.event.comm.TopicListener;
34 import org.onap.policy.common.endpoints.event.comm.TopicSink;
35 import org.onap.policy.common.endpoints.event.comm.TopicSource;
36 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
37 import org.onap.policy.common.utils.services.FeatureApiUtils;
38 import org.onap.policy.drools.controller.DroolsController;
39 import org.onap.policy.drools.controller.DroolsControllerConstants;
40 import org.onap.policy.drools.controller.DroolsControllerFactory;
41 import org.onap.policy.drools.features.PolicyControllerFeatureApi;
42 import org.onap.policy.drools.features.PolicyControllerFeatureApiConstants;
43 import org.onap.policy.drools.persistence.SystemPersistence;
44 import org.onap.policy.drools.persistence.SystemPersistenceConstants;
45 import org.onap.policy.drools.properties.DroolsPropertyConstants;
46 import org.onap.policy.drools.protocol.configuration.DroolsConfiguration;
47 import org.onap.policy.drools.system.PolicyController;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 * This implementation of the Policy Controller merely aggregates and tracks for management purposes
54 * all underlying resources that this controller depends upon.
56 public class AggregatedPolicyController implements PolicyController, TopicListener {
58 private static final String BEFORE_OFFER_FAILURE = "{}: feature {} before-offer failure because of {}";
59 private static final String AFTER_OFFER_FAILURE = "{}: feature {} after-offer failure because of {}";
64 private static final Logger logger = LoggerFactory.getLogger(AggregatedPolicyController.class);
67 * identifier for this policy controller.
69 private final String name;
72 * Abstracted Event Sources List regardless communication technology.
74 private final List<TopicSource> sources;
77 * Abstracted Event Sinks List regardless communication technology.
79 private final List<TopicSink> sinks;
82 * Mapping topics to sinks.
86 private final HashMap<String, TopicSink> topic2Sinks = new HashMap<>();
89 * Is this Policy Controller running (alive) ? reflects invocation of start()/stop() only.
91 private volatile boolean alive;
94 * Is this Policy Controller locked ? reflects if i/o controller related operations and start
95 * are permitted, more specifically: start(), deliver() and onTopicEvent(). It does not affect
96 * the ability to stop the underlying drools infrastructure
98 private volatile boolean locked;
101 * Policy Drools Controller.
103 private volatile DroolsController droolsController;
106 * Properties used to initialize controller.
108 private final Properties properties;
113 private List<ToscaPolicyTypeIdentifier> policyTypes;
116 * Constructor version mainly used for bootstrapping at initialization time a policy engine
119 * @param name controller name
122 * @throws IllegalArgumentException when invalid arguments are provided
124 public AggregatedPolicyController(String name, Properties properties) {
129 * 1. Register read topics with network infrastructure (ueb, dmaap, rest) 2. Register write
130 * topics with network infrastructure (ueb, dmaap, rest) 3. Register with drools
134 // Create/Reuse Readers/Writers for all event sources endpoints
136 this.sources = getEndpointManager().addTopicSources(properties);
137 this.sinks = getEndpointManager().addTopicSinks(properties);
139 initDrools(properties);
142 /* persist new properties */
143 getPersistenceManager().storeController(name, properties);
144 this.properties = properties;
146 this.policyTypes = getPolicyTypesFromProperties();
150 public List<ToscaPolicyTypeIdentifier> getPolicyTypes() {
151 if (!policyTypes.isEmpty()) {
155 return droolsController
156 .getBaseDomainNames()
158 .map(d -> new ToscaPolicyTypeIdentifier(d,
159 DroolsPropertyConstants.DEFAULT_CONTROLLER_POLICY_TYPE_VERSION))
160 .collect(Collectors.toList());
163 protected List<ToscaPolicyTypeIdentifier> getPolicyTypesFromProperties() {
164 List<ToscaPolicyTypeIdentifier> policyTypeIds = new ArrayList<>();
166 String ptiPropValue = properties.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_POLICY_TYPES);
167 if (ptiPropValue == null) {
168 return policyTypeIds;
171 List<String> ptiPropList = new ArrayList<>(Arrays.asList(ptiPropValue.split("\\s*,\\s*")));
172 for (String pti : ptiPropList) {
173 String[] ptv = pti.split(":");
174 if (ptv.length == 1) {
175 policyTypeIds.add(new ToscaPolicyTypeIdentifier(ptv[0],
176 DroolsPropertyConstants.DEFAULT_CONTROLLER_POLICY_TYPE_VERSION));
177 } else if (ptv.length == 2) {
178 policyTypeIds.add(new ToscaPolicyTypeIdentifier(ptv[0], ptv[1]));
182 return policyTypeIds;
186 * initialize drools layer.
188 * @throws IllegalArgumentException if invalid parameters are passed in
190 private void initDrools(Properties properties) {
192 // Register with drools infrastructure
193 this.droolsController = getDroolsFactory().build(properties, sources, sinks);
194 } catch (Exception | LinkageError e) {
195 logger.error("{}: cannot init-drools because of {}", this, e.getMessage(), e);
196 throw new IllegalArgumentException(e);
203 * @throws IllegalArgumentException if invalid parameters are passed in
205 private void initSinks() {
206 this.topic2Sinks.clear();
207 for (TopicSink sink : sinks) {
208 this.topic2Sinks.put(sink.getTopic(), sink);
216 public boolean updateDrools(DroolsConfiguration newDroolsConfiguration) {
218 DroolsConfiguration oldDroolsConfiguration = new DroolsConfiguration(this.droolsController.getArtifactId(),
219 this.droolsController.getGroupId(), this.droolsController.getVersion());
221 if (oldDroolsConfiguration.getGroupId().equalsIgnoreCase(newDroolsConfiguration.getGroupId())
222 && oldDroolsConfiguration.getArtifactId().equalsIgnoreCase(newDroolsConfiguration.getArtifactId())
223 && oldDroolsConfiguration.getVersion().equalsIgnoreCase(newDroolsConfiguration.getVersion())) {
224 logger.warn("{}: cannot update-drools: identical configuration {} vs {}", this, oldDroolsConfiguration,
225 newDroolsConfiguration);
230 /* Drools Controller created, update initialization properties for restarts */
232 this.properties.setProperty(DroolsPropertyConstants.RULES_GROUPID, newDroolsConfiguration.getGroupId());
233 this.properties.setProperty(DroolsPropertyConstants.RULES_ARTIFACTID,
234 newDroolsConfiguration.getArtifactId());
235 this.properties.setProperty(DroolsPropertyConstants.RULES_VERSION, newDroolsConfiguration.getVersion());
237 getPersistenceManager().storeController(name, this.properties);
239 this.initDrools(this.properties);
241 /* set drools controller to current locked status */
243 if (this.isLocked()) {
244 this.droolsController.lock();
246 this.droolsController.unlock();
249 /* set drools controller to current alive status */
251 if (this.isAlive()) {
252 this.droolsController.start();
254 this.droolsController.stop();
257 } catch (IllegalArgumentException e) {
258 logger.error("{}: cannot update-drools because of {}", this, e.getMessage(), e);
269 public String getName() {
277 public boolean start() {
278 logger.info("{}: start", this);
280 if (FeatureApiUtils.apply(getProviders(),
281 feature -> feature.beforeStart(this),
282 (feature, ex) -> logger.error("{}: feature {} before-start failure because of {}", this,
283 feature.getClass().getName(), ex.getMessage(), ex))) {
287 if (this.isLocked()) {
288 throw new IllegalStateException("Policy Controller " + name + " is locked");
291 synchronized (this) {
299 final boolean success = this.droolsController.start();
301 // register for events
303 for (TopicSource source : sources) {
304 source.register(this);
307 for (TopicSink sink : sinks) {
310 } catch (Exception e) {
311 logger.error("{}: cannot start {} because of {}", this, sink, e.getMessage(), e);
315 FeatureApiUtils.apply(getProviders(),
316 feature -> feature.afterStart(this),
317 (feature, ex) -> logger.error("{}: feature {} after-start failure because of {}", this,
318 feature.getClass().getName(), ex.getMessage(), ex));
327 public boolean stop() {
328 logger.info("{}: stop", this);
330 if (FeatureApiUtils.apply(getProviders(),
331 feature -> feature.beforeStop(this),
332 (feature, ex) -> logger.error("{}: feature {} before-stop failure because of {}", this,
333 feature.getClass().getName(), ex.getMessage(), ex))) {
337 /* stop regardless locked state */
339 synchronized (this) {
347 // 1. Stop registration
349 for (TopicSource source : sources) {
350 source.unregister(this);
353 boolean success = this.droolsController.stop();
355 FeatureApiUtils.apply(getProviders(),
356 feature -> feature.afterStop(this),
357 (feature, ex) -> logger.error("{}: feature {} after-stop failure because of {}", this,
358 feature.getClass().getName(), ex.getMessage(), ex));
367 public void shutdown() {
368 logger.info("{}: shutdown", this);
370 if (FeatureApiUtils.apply(getProviders(),
371 feature -> feature.beforeShutdown(this),
372 (feature, ex) -> logger.error("{}: feature {} before-shutdown failure because of {}", this,
373 feature.getClass().getName(), ex.getMessage(), ex))) {
379 getDroolsFactory().shutdown(this.droolsController);
381 FeatureApiUtils.apply(getProviders(),
382 feature -> feature.afterShutdown(this),
383 (feature, ex) -> logger.error("{}: feature {} after-shutdown failure because of {}", this,
384 feature.getClass().getName(), ex.getMessage(), ex));
392 logger.info("{}: halt", this);
394 if (FeatureApiUtils.apply(getProviders(),
395 feature -> feature.beforeHalt(this),
396 (feature, ex) -> logger.error("{}: feature {} before-halt failure because of {}", this,
397 feature.getClass().getName(), ex.getMessage(), ex))) {
402 getDroolsFactory().destroy(this.droolsController);
403 getPersistenceManager().deleteController(this.name);
405 FeatureApiUtils.apply(getProviders(),
406 feature -> feature.afterHalt(this),
407 (feature, ex) -> logger.error("{}: feature {} after-halt failure because of {}", this,
408 feature.getClass().getName(), ex.getMessage(), ex));
415 public void onTopicEvent(Topic.CommInfrastructure commType, String topic, String event) {
416 logger.debug("{}: raw event offered from {}:{}: {}", this, commType, topic, event);
422 if (FeatureApiUtils.apply(getProviders(),
423 feature -> feature.beforeOffer(this, commType, topic, event),
424 (feature, ex) -> logger.error(BEFORE_OFFER_FAILURE, this,
425 feature.getClass().getName(), ex.getMessage(), ex))) {
429 boolean success = this.droolsController.offer(topic, event);
431 FeatureApiUtils.apply(getProviders(),
432 feature -> feature.afterOffer(this, commType, topic, event, success),
433 (feature, ex) -> logger.error(AFTER_OFFER_FAILURE, this,
434 feature.getClass().getName(), ex.getMessage(), ex));
438 public <T> boolean offer(T event) {
439 logger.debug("{}: event offered: {}", this, event);
445 if (FeatureApiUtils.apply(getProviders(),
446 feature -> feature.beforeOffer(this, event),
447 (feature, ex) -> logger.error(BEFORE_OFFER_FAILURE, this,
448 feature.getClass().getName(), ex.getMessage(), ex))) {
452 boolean success = this.droolsController.offer(event);
454 FeatureApiUtils.apply(getProviders(),
455 feature -> feature.afterOffer(this, event, success),
456 (feature, ex) -> logger.error(AFTER_OFFER_FAILURE, this,
457 feature.getClass().getName(), ex.getMessage(), ex));
462 private boolean skipOffer() {
463 return isLocked() || !isAlive();
470 public boolean deliver(Topic.CommInfrastructure commType, String topic, Object event) {
472 logger.debug("{}: deliver event to {}:{}: {}", this, commType, topic, event);
474 if (FeatureApiUtils.apply(getProviders(),
475 feature -> feature.beforeDeliver(this, commType, topic, event),
476 (feature, ex) -> logger.error("{}: feature {} before-deliver failure because of {}", this,
477 feature.getClass().getName(), ex.getMessage(), ex))) {
481 if (topic == null || topic.isEmpty()) {
482 throw new IllegalArgumentException("Invalid Topic");
486 throw new IllegalArgumentException("Invalid Event");
489 if (!this.isAlive()) {
490 throw new IllegalStateException("Policy Engine is stopped");
493 if (this.isLocked()) {
494 throw new IllegalStateException("Policy Engine is locked");
497 if (!this.topic2Sinks.containsKey(topic)) {
498 logger.warn("{}: cannot deliver event because the sink {}:{} is not registered: {}", this, commType, topic,
500 throw new IllegalArgumentException("Unsupported topic " + topic + " for delivery");
503 boolean success = this.droolsController.deliver(this.topic2Sinks.get(topic), event);
505 FeatureApiUtils.apply(getProviders(),
506 feature -> feature.afterDeliver(this, commType, topic, event, success),
507 (feature, ex) -> logger.error("{}: feature {} after-deliver failure because of {}", this,
508 feature.getClass().getName(), ex.getMessage(), ex));
517 public boolean isAlive() {
525 public boolean lock() {
526 logger.info("{}: lock", this);
528 if (FeatureApiUtils.apply(getProviders(),
529 feature -> feature.beforeLock(this),
530 (feature, ex) -> logger.error("{}: feature {} before-lock failure because of {}", this,
531 feature.getClass().getName(), ex.getMessage(), ex))) {
535 synchronized (this) {
543 // it does not affect associated sources/sinks, they are
544 // autonomous entities
546 boolean success = this.droolsController.lock();
548 FeatureApiUtils.apply(getProviders(),
549 feature -> feature.afterLock(this),
550 (feature, ex) -> logger.error("{}: feature {} after-lock failure because of {}", this,
551 feature.getClass().getName(), ex.getMessage(), ex));
560 public boolean unlock() {
562 logger.info("{}: unlock", this);
564 if (FeatureApiUtils.apply(getProviders(),
565 feature -> feature.beforeUnlock(this),
566 (feature, ex) -> logger.error("{}: feature {} before-unlock failure because of {}", this,
567 feature.getClass().getName(), ex.getMessage(), ex))) {
571 synchronized (this) {
579 boolean success = this.droolsController.unlock();
581 FeatureApiUtils.apply(getProviders(),
582 feature -> feature.afterUnlock(this),
583 (feature, ex) -> logger.error("{}: feature {} after-unlock failure because of {}", this,
584 feature.getClass().getName(), ex.getMessage(), ex));
593 public boolean isLocked() {
601 public List<TopicSource> getTopicSources() {
609 public List<TopicSink> getTopicSinks() {
617 public DroolsController getDrools() {
618 return this.droolsController;
628 public Properties getProperties() {
629 return this.properties;
633 public String toString() {
634 return "AggregatedPolicyController [name=" + name + ", alive=" + alive
635 + ", locked=" + locked + ", droolsController=" + droolsController + "]";
638 // the following methods may be overridden by junit tests
640 protected SystemPersistence getPersistenceManager() {
641 return SystemPersistenceConstants.getManager();
644 protected TopicEndpoint getEndpointManager() {
645 return TopicEndpointManager.getManager();
648 protected DroolsControllerFactory getDroolsFactory() {
649 return DroolsControllerConstants.getFactory();
652 protected List<PolicyControllerFeatureApi> getProviders() {
653 return PolicyControllerFeatureApiConstants.getProviders().getList();