aa57abaf2f98df39c150c3f9cd044ac8c9c9c10f
[policy/drools-pdp.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * policy-management
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
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.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * This implementation of the Policy Controller merely aggregates and tracks for management purposes
54  * all underlying resources that this controller depends upon.
55  */
56 public class AggregatedPolicyController implements PolicyController, TopicListener {
57
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 {}";
60
61     /**
62      * Logger.
63      */
64     private static final Logger logger = LoggerFactory.getLogger(AggregatedPolicyController.class);
65
66     /**
67      * identifier for this policy controller.
68      */
69     private final String name;
70
71     /**
72      * Abstracted Event Sources List regardless communication technology.
73      */
74     private final List<TopicSource> sources;
75
76     /**
77      * Abstracted Event Sinks List regardless communication technology.
78      */
79     private final List<TopicSink> sinks;
80
81     /**
82      * Mapping topics to sinks.
83      */
84     @JsonIgnore
85     @GsonJsonIgnore
86     private final HashMap<String, TopicSink> topic2Sinks = new HashMap<>();
87
88     /**
89      * Is this Policy Controller running (alive) ? reflects invocation of start()/stop() only.
90      */
91     private volatile boolean alive;
92
93     /**
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
97      */
98     private volatile boolean locked;
99
100     /**
101      * Policy Drools Controller.
102      */
103     private volatile DroolsController droolsController;
104
105     /**
106      * Properties used to initialize controller.
107      */
108     private final Properties properties;
109
110     /**
111      * Policy Types.
112      */
113     private List<ToscaPolicyTypeIdentifier> policyTypes;
114
115     /**
116      * Constructor version mainly used for bootstrapping at initialization time a policy engine
117      * controller.
118      *
119      * @param name controller name
120      * @param properties
121      *
122      * @throws IllegalArgumentException when invalid arguments are provided
123      */
124     public AggregatedPolicyController(String name, Properties properties) {
125
126         this.name = name;
127
128         /*
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
131          * infrastructure
132          */
133
134         // Create/Reuse Readers/Writers for all event sources endpoints
135
136         this.sources = getEndpointManager().addTopicSources(properties);
137         this.sinks = getEndpointManager().addTopicSinks(properties);
138
139         initDrools(properties);
140         initSinks();
141
142         /* persist new properties */
143         getPersistenceManager().storeController(name, properties);
144         this.properties = properties;
145
146         this.policyTypes = getPolicyTypesFromProperties();
147     }
148
149     @Override
150     public List<ToscaPolicyTypeIdentifier> getPolicyTypes() {
151         if (!policyTypes.isEmpty()) {
152             return policyTypes;
153         }
154
155         return droolsController
156                 .getBaseDomainNames()
157                 .stream()
158                 .map(d -> new ToscaPolicyTypeIdentifier(d,
159                                 DroolsPropertyConstants.DEFAULT_CONTROLLER_POLICY_TYPE_VERSION))
160                 .collect(Collectors.toList());
161     }
162
163     protected List<ToscaPolicyTypeIdentifier> getPolicyTypesFromProperties() {
164         List<ToscaPolicyTypeIdentifier> policyTypeIds = new ArrayList<>();
165
166         String ptiPropValue = properties.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_POLICY_TYPES);
167         if (ptiPropValue == null) {
168             return policyTypeIds;
169         }
170
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]));
179             }
180         }
181
182         return policyTypeIds;
183     }
184
185     /**
186      * initialize drools layer.
187      *
188      * @throws IllegalArgumentException if invalid parameters are passed in
189      */
190     private void initDrools(Properties properties) {
191         try {
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);
197         }
198     }
199
200     /**
201      * initialize sinks.
202      *
203      * @throws IllegalArgumentException if invalid parameters are passed in
204      */
205     private void initSinks() {
206         this.topic2Sinks.clear();
207         for (TopicSink sink : sinks) {
208             this.topic2Sinks.put(sink.getTopic(), sink);
209         }
210     }
211
212     /**
213      * {@inheritDoc}.
214      */
215     @Override
216     public boolean updateDrools(DroolsConfiguration newDroolsConfiguration) {
217
218         DroolsConfiguration oldDroolsConfiguration = new DroolsConfiguration(this.droolsController.getArtifactId(),
219                 this.droolsController.getGroupId(), this.droolsController.getVersion());
220
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);
226             return true;
227         }
228
229         try {
230             /* Drools Controller created, update initialization properties for restarts */
231
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());
236
237             getPersistenceManager().storeController(name, this.properties);
238
239             this.initDrools(this.properties);
240
241             /* set drools controller to current locked status */
242
243             if (this.isLocked()) {
244                 this.droolsController.lock();
245             } else {
246                 this.droolsController.unlock();
247             }
248
249             /* set drools controller to current alive status */
250
251             if (this.isAlive()) {
252                 this.droolsController.start();
253             } else {
254                 this.droolsController.stop();
255             }
256
257         } catch (IllegalArgumentException e) {
258             logger.error("{}: cannot update-drools because of {}", this, e.getMessage(), e);
259             return false;
260         }
261
262         return true;
263     }
264
265     /**
266      * {@inheritDoc}.
267      */
268     @Override
269     public String getName() {
270         return this.name;
271     }
272
273     /**
274      * {@inheritDoc}.
275      */
276     @Override
277     public boolean start() {
278         logger.info("{}: start", this);
279
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))) {
284             return true;
285         }
286
287         if (this.isLocked()) {
288             throw new IllegalStateException("Policy Controller " + name + " is locked");
289         }
290
291         synchronized (this) {
292             if (this.alive) {
293                 return true;
294             }
295
296             this.alive = true;
297         }
298
299         final boolean success = this.droolsController.start();
300
301         // register for events
302
303         for (TopicSource source : sources) {
304             source.register(this);
305         }
306
307         for (TopicSink sink : sinks) {
308             try {
309                 sink.start();
310             } catch (Exception e) {
311                 logger.error("{}: cannot start {} because of {}", this, sink, e.getMessage(), e);
312             }
313         }
314
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));
319
320         return success;
321     }
322
323     /**
324      * {@inheritDoc}.
325      */
326     @Override
327     public boolean stop() {
328         logger.info("{}: stop", this);
329
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))) {
334             return true;
335         }
336
337         /* stop regardless locked state */
338
339         synchronized (this) {
340             if (!this.alive) {
341                 return true;
342             }
343
344             this.alive = false;
345         }
346
347         // 1. Stop registration
348
349         for (TopicSource source : sources) {
350             source.unregister(this);
351         }
352
353         boolean success = this.droolsController.stop();
354
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));
359
360         return success;
361     }
362
363     /**
364      * {@inheritDoc}.
365      */
366     @Override
367     public void shutdown() {
368         logger.info("{}: shutdown", this);
369
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))) {
374             return;
375         }
376
377         this.stop();
378
379         getDroolsFactory().shutdown(this.droolsController);
380
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));
385     }
386
387     /**
388      * {@inheritDoc}.
389      */
390     @Override
391     public void halt() {
392         logger.info("{}: halt", this);
393
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))) {
398             return;
399         }
400
401         this.stop();
402         getDroolsFactory().destroy(this.droolsController);
403         getPersistenceManager().deleteController(this.name);
404
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));
409     }
410
411     /**
412      * {@inheritDoc}.
413      */
414     @Override
415     public void onTopicEvent(Topic.CommInfrastructure commType, String topic, String event) {
416         logger.debug("{}: raw event offered from {}:{}: {}", this, commType, topic, event);
417
418         if (skipOffer()) {
419             return;
420         }
421
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))) {
426             return;
427         }
428
429         boolean success = this.droolsController.offer(topic, event);
430
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));
435     }
436
437     @Override
438     public <T> boolean offer(T event) {
439         logger.debug("{}: event offered: {}", this, event);
440
441         if (skipOffer()) {
442             return true;
443         }
444
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))) {
449             return true;
450         }
451
452         boolean success = this.droolsController.offer(event);
453
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));
458
459         return success;
460     }
461
462     private boolean skipOffer() {
463         return isLocked() || !isAlive();
464     }
465
466     /**
467      * {@inheritDoc}.
468      */
469     @Override
470     public boolean deliver(Topic.CommInfrastructure commType, String topic, Object event) {
471
472         logger.debug("{}: deliver event to {}:{}: {}", this, commType, topic, event);
473
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))) {
478             return true;
479         }
480
481         if (topic == null || topic.isEmpty()) {
482             throw new IllegalArgumentException("Invalid Topic");
483         }
484
485         if (event == null) {
486             throw new IllegalArgumentException("Invalid Event");
487         }
488
489         if (!this.isAlive()) {
490             throw new IllegalStateException("Policy Engine is stopped");
491         }
492
493         if (this.isLocked()) {
494             throw new IllegalStateException("Policy Engine is locked");
495         }
496
497         if (!this.topic2Sinks.containsKey(topic)) {
498             logger.warn("{}: cannot deliver event because the sink {}:{} is not registered: {}", this, commType, topic,
499                     event);
500             throw new IllegalArgumentException("Unsupported topic " + topic + " for delivery");
501         }
502
503         boolean success = this.droolsController.deliver(this.topic2Sinks.get(topic), event);
504
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));
509
510         return success;
511     }
512
513     /**
514      * {@inheritDoc}.
515      */
516     @Override
517     public boolean isAlive() {
518         return this.alive;
519     }
520
521     /**
522      * {@inheritDoc}.
523      */
524     @Override
525     public boolean lock() {
526         logger.info("{}: lock", this);
527
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))) {
532             return true;
533         }
534
535         synchronized (this) {
536             if (this.locked) {
537                 return true;
538             }
539
540             this.locked = true;
541         }
542
543         // it does not affect associated sources/sinks, they are
544         // autonomous entities
545
546         boolean success = this.droolsController.lock();
547
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));
552
553         return success;
554     }
555
556     /**
557      * {@inheritDoc}.
558      */
559     @Override
560     public boolean unlock() {
561
562         logger.info("{}: unlock", this);
563
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))) {
568             return true;
569         }
570
571         synchronized (this) {
572             if (!this.locked) {
573                 return true;
574             }
575
576             this.locked = false;
577         }
578
579         boolean success = this.droolsController.unlock();
580
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));
585
586         return success;
587     }
588
589     /**
590      * {@inheritDoc}.
591      */
592     @Override
593     public boolean isLocked() {
594         return this.locked;
595     }
596
597     /**
598      * {@inheritDoc}.
599      */
600     @Override
601     public List<TopicSource> getTopicSources() {
602         return this.sources;
603     }
604
605     /**
606      * {@inheritDoc}.
607      */
608     @Override
609     public List<TopicSink> getTopicSinks() {
610         return this.sinks;
611     }
612
613     /**
614      * {@inheritDoc}.
615      */
616     @Override
617     public DroolsController getDrools() {
618         return this.droolsController;
619     }
620
621
622     /**
623      * {@inheritDoc}.
624      */
625     @Override
626     @JsonIgnore
627     @GsonJsonIgnore
628     public Properties getProperties() {
629         return this.properties;
630     }
631
632     @Override
633     public String toString() {
634         return "AggregatedPolicyController [name=" + name + ", alive=" + alive
635                 + ", locked=" + locked + ", droolsController=" + droolsController + "]";
636     }
637
638     // the following methods may be overridden by junit tests
639
640     protected SystemPersistence getPersistenceManager() {
641         return SystemPersistenceConstants.getManager();
642     }
643
644     protected TopicEndpoint getEndpointManager() {
645         return TopicEndpointManager.getManager();
646     }
647
648     protected DroolsControllerFactory getDroolsFactory() {
649         return DroolsControllerConstants.getFactory();
650     }
651
652     protected List<PolicyControllerFeatureApi> getProviders() {
653         return PolicyControllerFeatureApiConstants.getProviders().getList();
654     }
655 }
656