2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-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.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.drools.utils.PropertyUtil;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * This implementation of the Policy Controller merely aggregates and tracks for management purposes
55 * all underlying resources that this controller depends upon.
57 public class AggregatedPolicyController implements PolicyController, TopicListener {
59 private static final String BEFORE_OFFER_FAILURE = "{}: feature {} before-offer failure because of {}";
60 private static final String AFTER_OFFER_FAILURE = "{}: feature {} after-offer failure because of {}";
65 private static final Logger logger = LoggerFactory.getLogger(AggregatedPolicyController.class);
68 * identifier for this policy controller.
70 private final String name;
73 * Abstracted Event Sources List regardless communication technology.
75 private final List<TopicSource> sources;
78 * Abstracted Event Sinks List regardless communication technology.
80 private final List<TopicSink> sinks;
83 * Mapping topics to sinks.
87 private final HashMap<String, TopicSink> topic2Sinks = new HashMap<>();
90 * Is this Policy Controller running (alive) ? reflects invocation of start()/stop() only.
92 private volatile boolean alive;
95 * Is this Policy Controller locked ? reflects if i/o controller related operations and start
96 * are permitted, more specifically: start(), deliver() and onTopicEvent(). It does not affect
97 * the ability to stop the underlying drools infrastructure
99 private volatile boolean locked;
102 * Policy Drools Controller.
104 private volatile DroolsController droolsController;
107 * Properties used to initialize controller.
109 private final Properties properties;
114 private List<ToscaPolicyTypeIdentifier> policyTypes;
117 * Constructor version mainly used for bootstrapping at initialization time a policy engine
120 * @param name controller name
123 * @throws IllegalArgumentException when invalid arguments are provided
125 public AggregatedPolicyController(String name, Properties properties) {
130 * 1. Register read topics with network infrastructure (ueb, dmaap, rest) 2. Register write
131 * topics with network infrastructure (ueb, dmaap, rest) 3. Register with drools
135 // Create/Reuse Readers/Writers for all event sources endpoints
137 this.sources = getEndpointManager().addTopicSources(properties);
138 this.sinks = getEndpointManager().addTopicSinks(properties);
140 initDrools(properties);
143 /* persist new properties */
144 getPersistenceManager().storeController(name, properties);
145 this.properties = PropertyUtil.getInterpolatedProperties(properties);
147 this.policyTypes = getPolicyTypesFromProperties();
151 public List<ToscaPolicyTypeIdentifier> getPolicyTypes() {
152 if (!policyTypes.isEmpty()) {
156 return droolsController
157 .getBaseDomainNames()
159 .map(d -> new ToscaPolicyTypeIdentifier(d,
160 DroolsPropertyConstants.DEFAULT_CONTROLLER_POLICY_TYPE_VERSION))
161 .collect(Collectors.toList());
164 protected List<ToscaPolicyTypeIdentifier> getPolicyTypesFromProperties() {
165 List<ToscaPolicyTypeIdentifier> policyTypeIds = new ArrayList<>();
167 String ptiPropValue = properties.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_POLICY_TYPES);
168 if (ptiPropValue == null) {
169 return policyTypeIds;
172 List<String> ptiPropList = new ArrayList<>(Arrays.asList(ptiPropValue.split("\\s*,\\s*")));
173 for (String pti : ptiPropList) {
174 String[] ptv = pti.split(":");
175 if (ptv.length == 1) {
176 policyTypeIds.add(new ToscaPolicyTypeIdentifier(ptv[0],
177 DroolsPropertyConstants.DEFAULT_CONTROLLER_POLICY_TYPE_VERSION));
178 } else if (ptv.length == 2) {
179 policyTypeIds.add(new ToscaPolicyTypeIdentifier(ptv[0], ptv[1]));
183 return policyTypeIds;
187 * initialize drools layer.
189 * @throws IllegalArgumentException if invalid parameters are passed in
191 private void initDrools(Properties properties) {
193 // Register with drools infrastructure
194 this.droolsController = getDroolsFactory().build(properties, sources, sinks);
195 } catch (Exception | LinkageError e) {
196 logger.error("{}: cannot init-drools because of {}", this, e.getMessage(), e);
197 throw new IllegalArgumentException(e);
204 * @throws IllegalArgumentException if invalid parameters are passed in
206 private void initSinks() {
207 this.topic2Sinks.clear();
208 for (TopicSink sink : sinks) {
209 this.topic2Sinks.put(sink.getTopic(), sink);
217 public boolean updateDrools(DroolsConfiguration newDroolsConfiguration) {
219 DroolsConfiguration oldDroolsConfiguration = new DroolsConfiguration(this.droolsController.getArtifactId(),
220 this.droolsController.getGroupId(), this.droolsController.getVersion());
222 if (oldDroolsConfiguration.getGroupId().equalsIgnoreCase(newDroolsConfiguration.getGroupId())
223 && oldDroolsConfiguration.getArtifactId().equalsIgnoreCase(newDroolsConfiguration.getArtifactId())
224 && oldDroolsConfiguration.getVersion().equalsIgnoreCase(newDroolsConfiguration.getVersion())) {
225 logger.warn("{}: cannot update-drools: identical configuration {} vs {}", this, oldDroolsConfiguration,
226 newDroolsConfiguration);
230 if (droolsController.isBrained()
231 && (newDroolsConfiguration.getArtifactId() == null
232 || DroolsControllerConstants.NO_ARTIFACT_ID.equals(newDroolsConfiguration.getArtifactId()))) {
233 DroolsControllerConstants.getFactory().destroy(this.droolsController);
237 /* Drools Controller created, update initialization properties for restarts */
239 this.properties.setProperty(DroolsPropertyConstants.RULES_GROUPID, newDroolsConfiguration.getGroupId());
240 this.properties.setProperty(DroolsPropertyConstants.RULES_ARTIFACTID,
241 newDroolsConfiguration.getArtifactId());
242 this.properties.setProperty(DroolsPropertyConstants.RULES_VERSION, newDroolsConfiguration.getVersion());
244 getPersistenceManager().storeController(name, this.properties);
246 this.initDrools(this.properties);
248 /* set drools controller to current locked status */
250 if (this.isLocked()) {
251 this.droolsController.lock();
253 this.droolsController.unlock();
256 /* set drools controller to current alive status */
258 if (this.isAlive()) {
259 this.droolsController.start();
261 this.droolsController.stop();
264 } catch (IllegalArgumentException e) {
265 logger.error("{}: cannot update-drools because of {}", this, e.getMessage(), e);
276 public String getName() {
284 public boolean start() {
285 logger.info("{}: start", this);
287 if (FeatureApiUtils.apply(getProviders(),
288 feature -> feature.beforeStart(this),
289 (feature, ex) -> logger.error("{}: feature {} before-start failure because of {}", this,
290 feature.getClass().getName(), ex.getMessage(), ex))) {
294 if (this.isLocked()) {
295 throw new IllegalStateException("Policy Controller " + name + " is locked");
298 synchronized (this) {
306 final boolean success = this.droolsController.start();
308 // register for events
310 for (TopicSource source : sources) {
311 source.register(this);
314 for (TopicSink sink : sinks) {
317 } catch (Exception e) {
318 logger.error("{}: cannot start {} because of {}", this, sink, e.getMessage(), e);
322 FeatureApiUtils.apply(getProviders(),
323 feature -> feature.afterStart(this),
324 (feature, ex) -> logger.error("{}: feature {} after-start failure because of {}", this,
325 feature.getClass().getName(), ex.getMessage(), ex));
334 public boolean stop() {
335 logger.info("{}: stop", this);
337 if (FeatureApiUtils.apply(getProviders(),
338 feature -> feature.beforeStop(this),
339 (feature, ex) -> logger.error("{}: feature {} before-stop failure because of {}", this,
340 feature.getClass().getName(), ex.getMessage(), ex))) {
344 /* stop regardless locked state */
346 synchronized (this) {
354 // 1. Stop registration
356 for (TopicSource source : sources) {
357 source.unregister(this);
360 boolean success = this.droolsController.stop();
362 FeatureApiUtils.apply(getProviders(),
363 feature -> feature.afterStop(this),
364 (feature, ex) -> logger.error("{}: feature {} after-stop failure because of {}", this,
365 feature.getClass().getName(), ex.getMessage(), ex));
374 public void shutdown() {
375 logger.info("{}: shutdown", this);
377 if (FeatureApiUtils.apply(getProviders(),
378 feature -> feature.beforeShutdown(this),
379 (feature, ex) -> logger.error("{}: feature {} before-shutdown failure because of {}", this,
380 feature.getClass().getName(), ex.getMessage(), ex))) {
386 getDroolsFactory().shutdown(this.droolsController);
388 FeatureApiUtils.apply(getProviders(),
389 feature -> feature.afterShutdown(this),
390 (feature, ex) -> logger.error("{}: feature {} after-shutdown failure because of {}", this,
391 feature.getClass().getName(), ex.getMessage(), ex));
399 logger.info("{}: halt", this);
401 if (FeatureApiUtils.apply(getProviders(),
402 feature -> feature.beforeHalt(this),
403 (feature, ex) -> logger.error("{}: feature {} before-halt failure because of {}", this,
404 feature.getClass().getName(), ex.getMessage(), ex))) {
409 getDroolsFactory().destroy(this.droolsController);
410 getPersistenceManager().deleteController(this.name);
412 FeatureApiUtils.apply(getProviders(),
413 feature -> feature.afterHalt(this),
414 (feature, ex) -> logger.error("{}: feature {} after-halt failure because of {}", this,
415 feature.getClass().getName(), ex.getMessage(), ex));
422 public void onTopicEvent(Topic.CommInfrastructure commType, String topic, String event) {
423 logger.debug("{}: raw event offered from {}:{}: {}", this, commType, topic, event);
429 if (FeatureApiUtils.apply(getProviders(),
430 feature -> feature.beforeOffer(this, commType, topic, event),
431 (feature, ex) -> logger.error(BEFORE_OFFER_FAILURE, this,
432 feature.getClass().getName(), ex.getMessage(), ex))) {
436 boolean success = this.droolsController.offer(topic, event);
438 FeatureApiUtils.apply(getProviders(),
439 feature -> feature.afterOffer(this, commType, topic, event, success),
440 (feature, ex) -> logger.error(AFTER_OFFER_FAILURE, this,
441 feature.getClass().getName(), ex.getMessage(), ex));
445 public <T> boolean offer(T event) {
446 logger.debug("{}: event offered: {}", this, event);
452 if (FeatureApiUtils.apply(getProviders(),
453 feature -> feature.beforeOffer(this, event),
454 (feature, ex) -> logger.error(BEFORE_OFFER_FAILURE, this,
455 feature.getClass().getName(), ex.getMessage(), ex))) {
459 boolean success = this.droolsController.offer(event);
461 FeatureApiUtils.apply(getProviders(),
462 feature -> feature.afterOffer(this, event, success),
463 (feature, ex) -> logger.error(AFTER_OFFER_FAILURE, this,
464 feature.getClass().getName(), ex.getMessage(), ex));
469 private boolean skipOffer() {
470 return isLocked() || !isAlive();
477 public boolean deliver(Topic.CommInfrastructure commType, String topic, Object event) {
479 logger.debug("{}: deliver event to {}:{}: {}", this, commType, topic, event);
481 if (FeatureApiUtils.apply(getProviders(),
482 feature -> feature.beforeDeliver(this, commType, topic, event),
483 (feature, ex) -> logger.error("{}: feature {} before-deliver failure because of {}", this,
484 feature.getClass().getName(), ex.getMessage(), ex))) {
488 if (topic == null || topic.isEmpty()) {
489 throw new IllegalArgumentException("Invalid Topic");
493 throw new IllegalArgumentException("Invalid Event");
496 if (!this.isAlive()) {
497 throw new IllegalStateException("Policy Engine is stopped");
500 if (this.isLocked()) {
501 throw new IllegalStateException("Policy Engine is locked");
504 if (!this.topic2Sinks.containsKey(topic)) {
505 logger.warn("{}: cannot deliver event because the sink {}:{} is not registered: {}", this, commType, topic,
507 throw new IllegalArgumentException("Unsupported topic " + topic + " for delivery");
510 boolean success = this.droolsController.deliver(this.topic2Sinks.get(topic), event);
512 FeatureApiUtils.apply(getProviders(),
513 feature -> feature.afterDeliver(this, commType, topic, event, success),
514 (feature, ex) -> logger.error("{}: feature {} after-deliver failure because of {}", this,
515 feature.getClass().getName(), ex.getMessage(), ex));
524 public boolean isAlive() {
532 public boolean lock() {
533 logger.info("{}: lock", this);
535 if (FeatureApiUtils.apply(getProviders(),
536 feature -> feature.beforeLock(this),
537 (feature, ex) -> logger.error("{}: feature {} before-lock failure because of {}", this,
538 feature.getClass().getName(), ex.getMessage(), ex))) {
542 synchronized (this) {
550 // it does not affect associated sources/sinks, they are
551 // autonomous entities
553 boolean success = this.droolsController.lock();
555 FeatureApiUtils.apply(getProviders(),
556 feature -> feature.afterLock(this),
557 (feature, ex) -> logger.error("{}: feature {} after-lock failure because of {}", this,
558 feature.getClass().getName(), ex.getMessage(), ex));
567 public boolean unlock() {
569 logger.info("{}: unlock", this);
571 if (FeatureApiUtils.apply(getProviders(),
572 feature -> feature.beforeUnlock(this),
573 (feature, ex) -> logger.error("{}: feature {} before-unlock failure because of {}", this,
574 feature.getClass().getName(), ex.getMessage(), ex))) {
578 synchronized (this) {
586 boolean success = this.droolsController.unlock();
588 FeatureApiUtils.apply(getProviders(),
589 feature -> feature.afterUnlock(this),
590 (feature, ex) -> logger.error("{}: feature {} after-unlock failure because of {}", this,
591 feature.getClass().getName(), ex.getMessage(), ex));
600 public boolean isLocked() {
608 public List<TopicSource> getTopicSources() {
616 public List<TopicSink> getTopicSinks() {
624 public DroolsController getDrools() {
625 return this.droolsController;
635 public Properties getProperties() {
636 return this.properties;
640 public String toString() {
641 return "AggregatedPolicyController [name=" + name + ", alive=" + alive
642 + ", locked=" + locked + ", droolsController=" + droolsController + "]";
645 // the following methods may be overridden by junit tests
647 protected SystemPersistence getPersistenceManager() {
648 return SystemPersistenceConstants.getManager();
651 protected TopicEndpoint getEndpointManager() {
652 return TopicEndpointManager.getManager();
655 protected DroolsControllerFactory getDroolsFactory() {
656 return DroolsControllerConstants.getFactory();
659 protected List<PolicyControllerFeatureApi> getProviders() {
660 return PolicyControllerFeatureApiConstants.getProviders().getList();