5685ff6eb38b25c429f50142034433e05ba80734
[policy/drools-pdp.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
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
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.system.internal;
22
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;
52
53 /**
54  * This implementation of the Policy Controller merely aggregates and tracks for management purposes
55  * all underlying resources that this controller depends upon.
56  */
57 public class AggregatedPolicyController implements PolicyController, TopicListener {
58
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 {}";
61
62     /**
63      * Logger.
64      */
65     private static final Logger logger = LoggerFactory.getLogger(AggregatedPolicyController.class);
66
67     /**
68      * identifier for this policy controller.
69      */
70     private final String name;
71
72     /**
73      * Abstracted Event Sources List regardless communication technology.
74      */
75     private final List<TopicSource> sources;
76
77     /**
78      * Abstracted Event Sinks List regardless communication technology.
79      */
80     private final List<TopicSink> sinks;
81
82     /**
83      * Mapping topics to sinks.
84      */
85     @JsonIgnore
86     @GsonJsonIgnore
87     private final HashMap<String, TopicSink> topic2Sinks = new HashMap<>();
88
89     /**
90      * Is this Policy Controller running (alive) ? reflects invocation of start()/stop() only.
91      */
92     private volatile boolean alive;
93
94     /**
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
98      */
99     private volatile boolean locked;
100
101     /**
102      * Policy Drools Controller.
103      */
104     private volatile DroolsController droolsController;
105
106     /**
107      * Properties used to initialize controller.
108      */
109     private final Properties properties;
110
111     /**
112      * Policy Types.
113      */
114     private List<ToscaPolicyTypeIdentifier> policyTypes;
115
116     /**
117      * Constructor version mainly used for bootstrapping at initialization time a policy engine
118      * controller.
119      *
120      * @param name controller name
121      * @param properties
122      *
123      * @throws IllegalArgumentException when invalid arguments are provided
124      */
125     public AggregatedPolicyController(String name, Properties properties) {
126
127         this.name = name;
128
129         /*
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
132          * infrastructure
133          */
134
135         // Create/Reuse Readers/Writers for all event sources endpoints
136
137         this.sources = getEndpointManager().addTopicSources(properties);
138         this.sinks = getEndpointManager().addTopicSinks(properties);
139
140         initDrools(properties);
141         initSinks();
142
143         /* persist new properties */
144         getPersistenceManager().storeController(name, properties);
145         this.properties = PropertyUtil.getInterpolatedProperties(properties);
146
147         this.policyTypes = getPolicyTypesFromProperties();
148     }
149
150     @Override
151     public List<ToscaPolicyTypeIdentifier> getPolicyTypes() {
152         if (!policyTypes.isEmpty()) {
153             return policyTypes;
154         }
155
156         return droolsController
157                 .getBaseDomainNames()
158                 .stream()
159                 .map(d -> new ToscaPolicyTypeIdentifier(d,
160                                 DroolsPropertyConstants.DEFAULT_CONTROLLER_POLICY_TYPE_VERSION))
161                 .collect(Collectors.toList());
162     }
163
164     protected List<ToscaPolicyTypeIdentifier> getPolicyTypesFromProperties() {
165         List<ToscaPolicyTypeIdentifier> policyTypeIds = new ArrayList<>();
166
167         String ptiPropValue = properties.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_POLICY_TYPES);
168         if (ptiPropValue == null) {
169             return policyTypeIds;
170         }
171
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]));
180             }
181         }
182
183         return policyTypeIds;
184     }
185
186     /**
187      * initialize drools layer.
188      *
189      * @throws IllegalArgumentException if invalid parameters are passed in
190      */
191     private void initDrools(Properties properties) {
192         try {
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);
198         }
199     }
200
201     /**
202      * initialize sinks.
203      *
204      * @throws IllegalArgumentException if invalid parameters are passed in
205      */
206     private void initSinks() {
207         this.topic2Sinks.clear();
208         for (TopicSink sink : sinks) {
209             this.topic2Sinks.put(sink.getTopic(), sink);
210         }
211     }
212
213     /**
214      * {@inheritDoc}.
215      */
216     @Override
217     public boolean updateDrools(DroolsConfiguration newDroolsConfiguration) {
218
219         DroolsConfiguration oldDroolsConfiguration = new DroolsConfiguration(this.droolsController.getArtifactId(),
220                 this.droolsController.getGroupId(), this.droolsController.getVersion());
221
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);
227             return true;
228         }
229
230         if (droolsController.isBrained()
231             && (newDroolsConfiguration.getArtifactId() == null
232                 || DroolsControllerConstants.NO_ARTIFACT_ID.equals(newDroolsConfiguration.getArtifactId()))) {
233             DroolsControllerConstants.getFactory().destroy(this.droolsController);
234         }
235
236         try {
237             /* Drools Controller created, update initialization properties for restarts */
238
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());
243
244             getPersistenceManager().storeController(name, this.properties);
245
246             this.initDrools(this.properties);
247
248             /* set drools controller to current locked status */
249
250             if (this.isLocked()) {
251                 this.droolsController.lock();
252             } else {
253                 this.droolsController.unlock();
254             }
255
256             /* set drools controller to current alive status */
257
258             if (this.isAlive()) {
259                 this.droolsController.start();
260             } else {
261                 this.droolsController.stop();
262             }
263
264         } catch (IllegalArgumentException e) {
265             logger.error("{}: cannot update-drools because of {}", this, e.getMessage(), e);
266             return false;
267         }
268
269         return true;
270     }
271
272     /**
273      * {@inheritDoc}.
274      */
275     @Override
276     public String getName() {
277         return this.name;
278     }
279
280     /**
281      * {@inheritDoc}.
282      */
283     @Override
284     public boolean start() {
285         logger.info("{}: start", this);
286
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))) {
291             return true;
292         }
293
294         if (this.isLocked()) {
295             throw new IllegalStateException("Policy Controller " + name + " is locked");
296         }
297
298         synchronized (this) {
299             if (this.alive) {
300                 return true;
301             }
302
303             this.alive = true;
304         }
305
306         final boolean success = this.droolsController.start();
307
308         // register for events
309
310         for (TopicSource source : sources) {
311             source.register(this);
312         }
313
314         for (TopicSink sink : sinks) {
315             try {
316                 sink.start();
317             } catch (Exception e) {
318                 logger.error("{}: cannot start {} because of {}", this, sink, e.getMessage(), e);
319             }
320         }
321
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));
326
327         return success;
328     }
329
330     /**
331      * {@inheritDoc}.
332      */
333     @Override
334     public boolean stop() {
335         logger.info("{}: stop", this);
336
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))) {
341             return true;
342         }
343
344         /* stop regardless locked state */
345
346         synchronized (this) {
347             if (!this.alive) {
348                 return true;
349             }
350
351             this.alive = false;
352         }
353
354         // 1. Stop registration
355
356         for (TopicSource source : sources) {
357             source.unregister(this);
358         }
359
360         boolean success = this.droolsController.stop();
361
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));
366
367         return success;
368     }
369
370     /**
371      * {@inheritDoc}.
372      */
373     @Override
374     public void shutdown() {
375         logger.info("{}: shutdown", this);
376
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))) {
381             return;
382         }
383
384         this.stop();
385
386         getDroolsFactory().shutdown(this.droolsController);
387
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));
392     }
393
394     /**
395      * {@inheritDoc}.
396      */
397     @Override
398     public void halt() {
399         logger.info("{}: halt", this);
400
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))) {
405             return;
406         }
407
408         this.stop();
409         getDroolsFactory().destroy(this.droolsController);
410         getPersistenceManager().deleteController(this.name);
411
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));
416     }
417
418     /**
419      * {@inheritDoc}.
420      */
421     @Override
422     public void onTopicEvent(Topic.CommInfrastructure commType, String topic, String event) {
423         logger.debug("{}: raw event offered from {}:{}: {}", this, commType, topic, event);
424
425         if (skipOffer()) {
426             return;
427         }
428
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))) {
433             return;
434         }
435
436         boolean success = this.droolsController.offer(topic, event);
437
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));
442     }
443
444     @Override
445     public <T> boolean offer(T event) {
446         logger.debug("{}: event offered: {}", this, event);
447
448         if (skipOffer()) {
449             return true;
450         }
451
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))) {
456             return true;
457         }
458
459         boolean success = this.droolsController.offer(event);
460
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));
465
466         return success;
467     }
468
469     private boolean skipOffer() {
470         return isLocked() || !isAlive();
471     }
472
473     /**
474      * {@inheritDoc}.
475      */
476     @Override
477     public boolean deliver(Topic.CommInfrastructure commType, String topic, Object event) {
478
479         logger.debug("{}: deliver event to {}:{}: {}", this, commType, topic, event);
480
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))) {
485             return true;
486         }
487
488         if (topic == null || topic.isEmpty()) {
489             throw new IllegalArgumentException("Invalid Topic");
490         }
491
492         if (event == null) {
493             throw new IllegalArgumentException("Invalid Event");
494         }
495
496         if (!this.isAlive()) {
497             throw new IllegalStateException("Policy Engine is stopped");
498         }
499
500         if (this.isLocked()) {
501             throw new IllegalStateException("Policy Engine is locked");
502         }
503
504         if (!this.topic2Sinks.containsKey(topic)) {
505             logger.warn("{}: cannot deliver event because the sink {}:{} is not registered: {}", this, commType, topic,
506                     event);
507             throw new IllegalArgumentException("Unsupported topic " + topic + " for delivery");
508         }
509
510         boolean success = this.droolsController.deliver(this.topic2Sinks.get(topic), event);
511
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));
516
517         return success;
518     }
519
520     /**
521      * {@inheritDoc}.
522      */
523     @Override
524     public boolean isAlive() {
525         return this.alive;
526     }
527
528     /**
529      * {@inheritDoc}.
530      */
531     @Override
532     public boolean lock() {
533         logger.info("{}: lock", this);
534
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))) {
539             return true;
540         }
541
542         synchronized (this) {
543             if (this.locked) {
544                 return true;
545             }
546
547             this.locked = true;
548         }
549
550         // it does not affect associated sources/sinks, they are
551         // autonomous entities
552
553         boolean success = this.droolsController.lock();
554
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));
559
560         return success;
561     }
562
563     /**
564      * {@inheritDoc}.
565      */
566     @Override
567     public boolean unlock() {
568
569         logger.info("{}: unlock", this);
570
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))) {
575             return true;
576         }
577
578         synchronized (this) {
579             if (!this.locked) {
580                 return true;
581             }
582
583             this.locked = false;
584         }
585
586         boolean success = this.droolsController.unlock();
587
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));
592
593         return success;
594     }
595
596     /**
597      * {@inheritDoc}.
598      */
599     @Override
600     public boolean isLocked() {
601         return this.locked;
602     }
603
604     /**
605      * {@inheritDoc}.
606      */
607     @Override
608     public List<TopicSource> getTopicSources() {
609         return this.sources;
610     }
611
612     /**
613      * {@inheritDoc}.
614      */
615     @Override
616     public List<TopicSink> getTopicSinks() {
617         return this.sinks;
618     }
619
620     /**
621      * {@inheritDoc}.
622      */
623     @Override
624     public DroolsController getDrools() {
625         return this.droolsController;
626     }
627
628
629     /**
630      * {@inheritDoc}.
631      */
632     @Override
633     @JsonIgnore
634     @GsonJsonIgnore
635     public Properties getProperties() {
636         return this.properties;
637     }
638
639     @Override
640     public String toString() {
641         return "AggregatedPolicyController [name=" + name + ", alive=" + alive
642                 + ", locked=" + locked + ", droolsController=" + droolsController + "]";
643     }
644
645     // the following methods may be overridden by junit tests
646
647     protected SystemPersistence getPersistenceManager() {
648         return SystemPersistenceConstants.getManager();
649     }
650
651     protected TopicEndpoint getEndpointManager() {
652         return TopicEndpointManager.getManager();
653     }
654
655     protected DroolsControllerFactory getDroolsFactory() {
656         return DroolsControllerConstants.getFactory();
657     }
658
659     protected List<PolicyControllerFeatureApi> getProviders() {
660         return PolicyControllerFeatureApiConstants.getProviders().getList();
661     }
662 }
663