aboutsummaryrefslogtreecommitdiffstats
path: root/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineManager.java
blob: 0bc2318bba349de579212875523c5c9ce46c2cc1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
/*
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
 * Modifications Copyright (C) 2024 Nordix Foundation.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.drools.system;

import static org.onap.policy.drools.system.PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_HOST;
import static org.onap.policy.drools.system.PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_NAME;
import static org.onap.policy.drools.system.PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_PORT;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.prometheus.client.Summary;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.Synchronized;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.common.endpoints.event.comm.Topic;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
import org.onap.policy.common.endpoints.event.comm.TopicSink;
import org.onap.policy.common.endpoints.event.comm.TopicSource;
import org.onap.policy.common.endpoints.http.client.HttpClient;
import org.onap.policy.common.endpoints.http.client.HttpClientFactory;
import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
import org.onap.policy.common.endpoints.http.server.HttpServletServer;
import org.onap.policy.common.endpoints.http.server.HttpServletServerFactory;
import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
import org.onap.policy.common.gson.annotation.GsonJsonProperty;
import org.onap.policy.common.utils.logging.LoggerUtils;
import org.onap.policy.common.utils.network.NetworkUtil;
import org.onap.policy.common.utils.resources.PrometheusUtils;
import org.onap.policy.common.utils.services.FeatureApiUtils;
import org.onap.policy.drools.controller.DroolsControllerConstants;
import org.onap.policy.drools.core.PolicyContainer;
import org.onap.policy.drools.core.jmx.PdpJmxListener;
import org.onap.policy.drools.core.lock.Lock;
import org.onap.policy.drools.core.lock.LockCallback;
import org.onap.policy.drools.core.lock.PolicyResourceLockManager;
import org.onap.policy.drools.features.PolicyControllerFeatureApi;
import org.onap.policy.drools.features.PolicyControllerFeatureApiConstants;
import org.onap.policy.drools.features.PolicyEngineFeatureApi;
import org.onap.policy.drools.features.PolicyEngineFeatureApiConstants;
import org.onap.policy.drools.metrics.Metric;
import org.onap.policy.drools.persistence.SystemPersistence;
import org.onap.policy.drools.persistence.SystemPersistenceConstants;
import org.onap.policy.drools.policies.DomainMaker;
import org.onap.policy.drools.properties.DroolsPropertyConstants;
import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
import org.onap.policy.drools.protocol.coders.EventProtocolCoderConstants;
import org.onap.policy.drools.protocol.configuration.ControllerConfiguration;
import org.onap.policy.drools.protocol.configuration.PdpdConfiguration;
import org.onap.policy.drools.server.restful.RestManager;
import org.onap.policy.drools.stats.PolicyStatsManager;
import org.onap.policy.drools.system.internal.SimpleLockManager;
import org.onap.policy.drools.utils.PropertyUtil;
import org.onap.policy.drools.utils.logging.MdcTransaction;
import org.onap.policy.models.pdp.enums.PdpResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Policy Engine Manager Implementation.
 */
@ToString(onlyExplicitlyIncluded = true)
class PolicyEngineManager implements PolicyEngine {
    /**
     * String literals.
     */
    private static final String INVALID_TOPIC_MSG = "Invalid Topic";
    private static final String INVALID_EVENT_MSG = "Invalid Event";

    private static final String ENGINE_STOPPED_MSG = "Policy Engine is stopped";
    private static final String ENGINE_LOCKED_MSG = "Policy Engine is locked";

    public static final String EXECUTOR_THREAD_PROP = "executor.threads";
    protected static final int DEFAULT_EXECUTOR_THREADS = 5;

    public static final String CLUSTER_NAME_PROP = "engine.cluster";

    /**
     * logger.
     */
    private static final Logger logger = LoggerFactory.getLogger(PolicyEngineManager.class);

    /**
     * Is the Policy Engine running.
     */
    @Getter
    @ToString.Include
    private volatile boolean alive = false;

    /**
     * Is the engine locked.
     */
    @Getter
    @ToString.Include
    private volatile boolean locked = false;

    /**
     * Properties used to initialize the engine.
     */
    private Properties properties;

    /**
     * Environment Properties.
     */
    private final Properties environment = new Properties();

    /**
     * Policy Engine Sources.
     */
    @Getter
    private List<TopicSource> sources = new ArrayList<>();

    /**
     * Policy Engine Sinks.
     */
    @Getter
    private List<TopicSink> sinks = new ArrayList<>();

    /**
     * Policy Engine HTTP Servers.
     */
    @Getter
    private List<HttpServletServer> httpServers = new ArrayList<>();

    /**
     * Thread pool used to execute background tasks.
     */
    private ScheduledExecutorService executorService = null;

    /**
     * Lock manager used to create locks.
     */
    @Getter(AccessLevel.PROTECTED)
    private PolicyResourceLockManager lockManager = null;

    private final DomainMaker domainMaker = new DomainMaker();

    @Getter
    private final PolicyStatsManager stats = new PolicyStatsManager();

    @Getter(onMethod_ = {@Synchronized})
    @Setter(onMethod_ = {@Synchronized})
    private String clusterName = UUID.randomUUID().toString();

    @Getter(onMethod_ = {@Synchronized})
    @Setter(onMethod_ = {@Synchronized})
    private String hostName = NetworkUtil.getHostname();

    @Getter(onMethod_ = {@Synchronized})
    @Setter(onMethod_ = {@Synchronized})
    private String pdpName;

    /**
     * gson parser to decode configuration requests.
     */
    private final Gson decoder = new GsonBuilder().disableHtmlEscaping().create();

    protected static final String CONTROLLOOP_NAME_LABEL = "controlloop";
    protected static final String CONTROLLER_LABEL = "controller";
    protected static final String POLICY_LABEL = "policy";

    protected static final Summary transLatencySecsSummary =
            Summary.build().namespace(PrometheusUtils.PdpType.PDPD.getNamespace())
                    .name(PrometheusUtils.POLICY_EXECUTIONS_LATENCY_SECONDS_METRIC)
                    .labelNames(CONTROLLER_LABEL,
                            CONTROLLOOP_NAME_LABEL,
                            POLICY_LABEL,
                            PrometheusUtils.STATUS_METRIC_LABEL)
                    .help(PrometheusUtils.POLICY_EXECUTIONS_LATENCY_SECONDS_HELP)
                    .register();


    @Override
    public synchronized void boot(String[] cliArgs) {

        if (FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.beforeBoot(this, cliArgs),
            (feature, ex) -> logger.error("{}: feature {} before-boot failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex))) {
            return;
        }

        try {
            globalInitContainer(cliArgs);
        } catch (final Exception e) {
            logger.error("{}: cannot init policy-container because of {}", this, e.getMessage(), e);
        }

        FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.afterBoot(this),
            (feature, ex) -> logger.error("{}: feature {} after-boot failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex));
    }

    @Override
    public synchronized void setEnvironment(Properties properties) {
        this.environment.putAll(PropertyUtil.getInterpolatedProperties(properties));
    }

    @GsonJsonIgnore
    @Override
    public synchronized Properties getEnvironment() {
        return this.environment;
    }

    @GsonJsonIgnore
    @Override
    public DomainMaker getDomainMaker() {
        return this.domainMaker;
    }

    @Override
    public synchronized String getEnvironmentProperty(String envKey) {
        String value = this.environment.getProperty(envKey);
        if (value == null) {
            value = System.getProperty(envKey);
            if (value == null) {
                value = System.getenv(envKey);
            }
        }
        return value;
    }

    @Override
    public synchronized String setEnvironmentProperty(String envKey, String envValue) {
        return (String) this.environment.setProperty(envKey, envValue);
    }

    @Override
    public final Properties defaultTelemetryConfig() {
        final var defaultConfig = new Properties();

        defaultConfig.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, "TELEMETRY");
        defaultConfig.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + TELEMETRY_SERVER_DEFAULT_NAME
                + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, TELEMETRY_SERVER_DEFAULT_HOST);
        defaultConfig.put(
                PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + TELEMETRY_SERVER_DEFAULT_NAME
                        + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
                "" + TELEMETRY_SERVER_DEFAULT_PORT);
        defaultConfig.put(
                PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + TELEMETRY_SERVER_DEFAULT_NAME
                        + PolicyEndPointProperties.PROPERTY_HTTP_REST_PACKAGES_SUFFIX,
                RestManager.class.getPackage().getName());
        defaultConfig.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + TELEMETRY_SERVER_DEFAULT_NAME
                + PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, "" + Boolean.TRUE);
        defaultConfig.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + TELEMETRY_SERVER_DEFAULT_NAME
                + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "" + Boolean.FALSE);

        return defaultConfig;
    }

    @Override
    public void metric(String controllerName, String policyName, Metric metric) {
        // sub-operations are not being tracked
    }

    @Override
    public void transaction(@NonNull String controllerName,                         // NOSONAR placeholder
            @NonNull String controlLoopName, @NonNull Metric transaction) {

        // keeping stats on a per control loop name,
        // applications must report the controller name too
        // for completeness and to avoid being modified when/if
        // the controller name is used for tracking purposes

        getStats().stat(controlLoopName, transaction);

        Long elapsedTime = transaction.getElapsedTime();
        String policyName = transaction.getServiceInstanceId();
        if (Objects.isNull(elapsedTime) || StringUtils.isEmpty(policyName)) {
            logger.warn("{} transaction in controller {} incomplete transaction object: {}",
                    controlLoopName, controllerName, transaction);
            return;
        }

        transLatencySecsSummary
            .labels(controllerName,
                    controlLoopName,
                    policyName,
                    transaction.isSuccess() ? PdpResponseStatus.SUCCESS.name() : PdpResponseStatus.FAIL.name())
            .observe(transaction.getElapsedTime() / 1000D);
    }

    @Override
    @GsonJsonIgnore
    public ScheduledExecutorService getExecutorService() {
        return executorService;
    }

    private ScheduledExecutorService makeExecutorService(Properties properties) {
        int nthreads = DEFAULT_EXECUTOR_THREADS;

        try {
            nthreads = Integer.parseInt(
                            properties.getProperty(EXECUTOR_THREAD_PROP, String.valueOf(DEFAULT_EXECUTOR_THREADS)));

        } catch (NumberFormatException e) {
            logger.error("invalid number for " + EXECUTOR_THREAD_PROP + " property", e);
        }

        return makeScheduledExecutor(nthreads);
    }

    private void createLockManager(Properties properties) {
        for (PolicyEngineFeatureApi feature : getEngineProviders()) {
            try {
                this.lockManager = feature.beforeCreateLockManager(this, properties);
                if (this.lockManager != null) {
                    logger.info("overridden lock manager is {}", this.lockManager);
                    return;
                }
            } catch (RuntimeException e) {
                logger.error("{}: feature {} before-create-lock-manager failure because of {}", this,
                                feature.getClass().getName(), e.getMessage(), e);
            }
        }

        try {
            this.lockManager = new SimpleLockManager(this, properties);
        } catch (RuntimeException e) {
            logger.error("{}: cannot create simple lock manager because of {}", this, e.getMessage(), e);
            this.lockManager = new SimpleLockManager(this, new Properties());
        }

        logger.info("lock manager is {}", this.lockManager);

        /* policy-engine dispatch post operation hook */
        FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.afterCreateLockManager(this, properties, this.lockManager),
            (feature, ex) -> logger.error("{}: feature {} after-create-lock-manager failure because of {}",
                            this, feature.getClass().getName(), ex.getMessage(), ex));
    }

    @Override
    public synchronized void configure(Properties properties) {

        if (properties == null) {
            logger.warn("No properties provided");
            throw new IllegalArgumentException("No properties provided");
        }

        /* policy-engine dispatch pre configure hook */
        if (FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.beforeConfigure(this, properties),
            (feature, ex) -> logger.error("{}: feature {} before-configure failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex))) {
            return;
        }

        this.properties = properties;
        if (!StringUtils.isBlank(this.properties.getProperty(CLUSTER_NAME_PROP))) {
            this.clusterName = this.properties.getProperty(CLUSTER_NAME_PROP, this.clusterName);
        }
        this.pdpName = hostName + "." + this.clusterName;

        try {
            this.sources = getTopicEndpointManager().addTopicSources(properties);
            for (final TopicSource source : this.sources) {
                source.register(this);
            }
        } catch (final Exception e) {
            logger.error("{}: add-sources failed", this, e);
        }

        try {
            this.sinks = getTopicEndpointManager().addTopicSinks(properties);
        } catch (final IllegalArgumentException e) {
            logger.error("{}: add-sinks failed", this, e);
        }

        try {
            this.httpServers = getServletFactory().build(properties);
        } catch (final IllegalArgumentException e) {
            logger.error("{}: add-http-servers failed", this, e);
        }

        executorService = makeExecutorService(properties);

        createLockManager(properties);

        /* policy-engine dispatch post configure hook */
        FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.afterConfigure(this),
            (feature, ex) -> logger.error("{}: feature {} after-configure failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex));
    }

    @Override
    public boolean configure(PdpdConfiguration config) {

        if (config == null) {
            throw new IllegalArgumentException("No configuration provided");
        }

        final String entity = config.getEntity();

        var mdcTrans = MdcTransaction.newTransaction(config.getRequestId(), "brmsgw");
        if (this.getSources().size() == 1) {
            Topic topic = this.getSources().get(0);
            mdcTrans.setServiceName(topic.getTopic()).setRemoteHost(topic.getServers().toString())
                    .setTargetEntity(config.getEntity());
        }


        if (PdpdConfiguration.CONFIG_ENTITY_CONTROLLER.equals(entity)) {
            boolean success = controllerConfig(config);
            mdcTrans.resetSubTransaction().setStatusCode(success).transaction();
            return success;

        } else {
            final String msg = "Configuration Entity is not supported: " + entity;
            mdcTrans.resetSubTransaction().setStatusCode(false).setResponseDescription(msg).flush();
            logger.warn(LoggerUtils.TRANSACTION_LOG_MARKER, msg);
            throw new IllegalArgumentException(msg);
        }
    }

    @Override
    public synchronized PolicyController createPolicyController(String name, Properties properties) {
        String tempName = name;
        // check if a PROPERTY_CONTROLLER_NAME property is present
        // if so, override the given name

        final String propertyControllerName = properties.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME);
        if (propertyControllerName != null && !propertyControllerName.isEmpty()) {
            if (!propertyControllerName.equals(tempName)) {
                throw new IllegalStateException("Proposed name (" + tempName + ") and properties name ("
                        + propertyControllerName + ") don't match");
            }
            tempName = propertyControllerName;
        }

        PolicyController controller;
        for (final PolicyControllerFeatureApi controllerFeature : getControllerProviders()) {
            try {
                controller = controllerFeature.beforeCreate(tempName, properties);
                if (controller != null) {
                    return controller;
                }
            } catch (final Exception e) {
                logger.error("{}: feature {} before-controller-create failure because of {}", this,
                        controllerFeature.getClass().getName(), e.getMessage(), e);
            }
        }

        controller = getControllerFactory().build(tempName, properties);
        if (this.isLocked()) {
            controller.lock();
        }

        // feature hook
        PolicyController controller2 = controller;
        FeatureApiUtils.apply(getControllerProviders(),
            feature -> feature.afterCreate(controller2),
            (feature, ex) -> logger.error("{}: feature {} after-controller-create failure because of {}",
                            this, feature.getClass().getName(), ex.getMessage(), ex));

        return controller;
    }


    @Override
    public List<PolicyController> updatePolicyControllers(List<ControllerConfiguration> configControllers) {

        final List<PolicyController> policyControllers = new ArrayList<>();
        if (configControllers == null || configControllers.isEmpty()) {
            logger.info("No controller configuration provided: {}", configControllers);
            return policyControllers;
        }

        for (final ControllerConfiguration configController : configControllers) {
            MdcTransaction mdcTrans = MdcTransaction.newSubTransaction(null).setTargetEntity(configController.getName())
                    .setTargetServiceName(configController.getOperation())
                    .setTargetVirtualEntity("" + configController.getDrools());
            try {
                var policyController = this.updatePolicyController(configController);
                policyControllers.add(policyController);
                mdcTrans.setStatusCode(true).transaction();
            } catch (final Exception e) {
                mdcTrans.setStatusCode(false).setResponseCode(e.getClass().getName())
                        .setResponseDescription(e.getMessage()).flush();
                logger.error(LoggerUtils.TRANSACTION_LOG_MARKER,
                        "{}: cannot update-policy-controllers because of {}", this, e.getMessage(), e);
            }
        }

        return policyControllers;
    }

    @Override
    public synchronized PolicyController updatePolicyController(ControllerConfiguration configController) {

        if (configController == null) {
            throw new IllegalArgumentException("No controller configuration has been provided");
        }

        final String controllerName = configController.getName();
        if (controllerName == null || controllerName.isEmpty()) {
            logger.warn("controller-name  must be provided");
            throw new IllegalArgumentException("No controller configuration has been provided");
        }

        try {
            final String operation = configController.getOperation();
            if (operation == null || operation.isEmpty()) {
                logger.warn("operation must be provided");
                throw new IllegalArgumentException("operation must be provided");
            }

            var policyController = getController(controllerName);
            if (policyController == null) {
                policyController = findController(controllerName, operation);

                /* fall through to do brain update operation */
            }

            updateController(controllerName, policyController, operation, configController);

            return policyController;
        } catch (final Exception e) {
            logger.error("{}: cannot update-policy-controller", this);
            throw e;
        } catch (final LinkageError e) {
            logger.error("{}: cannot update-policy-controllers (rules)", this);
            throw new IllegalStateException(e);
        }
    }

    private PolicyController getController(final String controllerName) {
        PolicyController policyController = null;
        try {
            policyController = getControllerFactory().get(controllerName);
        } catch (final IllegalArgumentException e) {
            // not found
            logger.warn("Policy Controller {} not found", controllerName, e);
        }
        return policyController;
    }

    private PolicyController findController(final String controllerName, final String operation) {
        if (operation.equalsIgnoreCase(ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_LOCK)
                || operation.equalsIgnoreCase(ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_UNLOCK)) {
            throw new IllegalArgumentException(controllerName + " is not available for operation " + operation);
        }

        /* Recovery case */

        logger.warn("controller {} does not exist. Attempting recovery from disk", controllerName);

        var controllerProperties =
                getPersistenceManager().getControllerProperties(controllerName);

        /*
         * returned properties cannot be null (per implementation) assert (properties !=
         * null)
         */

        if (controllerProperties == null) {
            throw new IllegalArgumentException(controllerName + " is invalid");
        }

        logger.warn("controller being recovered. {} Reset controller's bad maven coordinates to brainless",
                controllerName);

        /*
         * try to bring up bad controller in brainless mode, after having it
         * working, apply the new create/update operation.
         */
        controllerProperties.setProperty(DroolsPropertyConstants.RULES_GROUPID,
                        DroolsControllerConstants.NO_GROUP_ID);
        controllerProperties.setProperty(DroolsPropertyConstants.RULES_ARTIFACTID,
                        DroolsControllerConstants.NO_ARTIFACT_ID);
        controllerProperties.setProperty(DroolsPropertyConstants.RULES_VERSION,
                        DroolsControllerConstants.NO_VERSION);

        return getPolicyEngine().createPolicyController(controllerName, controllerProperties);
    }

    private void updateController(final String controllerName, PolicyController policyController,
                    final String operation, ControllerConfiguration configController) {
        switch (operation) {
            case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_CREATE:
                getControllerFactory().patch(policyController, configController.getDrools());
                break;
            case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_UPDATE:
                policyController.unlock();
                getControllerFactory().patch(policyController, configController.getDrools());
                break;
            case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_LOCK:
                policyController.lock();
                break;
            case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_UNLOCK:
                policyController.unlock();
                break;
            default:
                final String msg = "Controller Operation Configuration is not supported: " + operation + " for "
                        + controllerName;
                logger.warn(msg);
                throw new IllegalArgumentException(msg);
        }
    }

    @Override
    public synchronized boolean start() {

        /* policy-engine dispatch pre start hook */
        if (FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.beforeStart(this),
            (feature, ex) -> logger.error("{}: feature {} before-start failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex))) {
            return true;
        }

        if (this.locked) {
            throw new IllegalStateException(ENGINE_LOCKED_MSG);
        }

        this.alive = true;

        AtomicReference<Boolean> success = new AtomicReference<>(true);

        try {
            success.compareAndSet(true, this.lockManager.start());
        } catch (final RuntimeException e) {
            logger.warn("{}: cannot start lock manager because of {}", this, e.getMessage(), e);
            success.set(false);
        }

        /* Start managed and unmanaged http servers */

        attempt(success,
            Stream.concat(getServletFactory().inventory().stream(), this.httpServers.stream())
                .collect(Collectors.toList()),
            httpServer -> httpServer.waitedStart(10 * 1000L),
            (item, ex) -> logger.error("{}: cannot start http-server {} because of {}", this, item,
                ex.getMessage(), ex));

        /* Start managed Http Clients */

        attempt(success, getHttpClientFactory().inventory(),
            HttpClient::start,
            (item, ex) -> logger.error("{}: cannot start http-client {} because of {}",
                this, item, ex.getMessage(), ex));

        /* Start Policy Controllers */

        attempt(success, getControllerFactory().inventory(),
            PolicyController::start,
            (item, ex) -> {
                logger.error("{}: cannot start policy-controller {} because of {}", this, item,
                                ex.getMessage(), ex);
                success.set(false);
            });

        /* Start managed Topic Endpoints */

        try {
            if (!getTopicEndpointManager().start()) {
                success.set(false);
            }
        } catch (final IllegalStateException e) {
            logger.warn("{}: Topic Endpoint Manager is in an invalid state because of {}", this, e.getMessage(), e);
        }

        // Start the JMX listener

        startPdpJmxListener();

        /* policy-engine dispatch after start hook */
        FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.afterStart(this),
            (feature, ex) -> logger.error("{}: feature {} after-start failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex));

        return success.get();
    }

    @Override
    public synchronized boolean open() {

        /* pre-open hook */
        if (FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.beforeOpen(this),
            (feature, ex) -> logger.error("{}: feature {} before-open failure because of {}", this,
                feature.getClass().getName(), ex.getMessage(), ex))) {
            return true;
        }

        if (this.locked) {
            throw new IllegalStateException(ENGINE_LOCKED_MSG);
        }

        if (!this.alive) {
            throw new IllegalStateException(ENGINE_STOPPED_MSG);
        }

        AtomicReference<Boolean> success = new AtomicReference<>(true);

        /* Open the unmanaged topics to external components for configuration purposes */

        attempt(success, this.sources,
            TopicSource::start,
            (item, ex) -> logger.error("{}: cannot start topic-source {} because of {}",
                this, item, ex.getMessage(), ex));

        attempt(success, this.sinks,
            TopicSink::start,
            (item, ex) -> logger.error("{}: cannot start topic-sink {} because of {}",
                this, item, ex.getMessage(), ex));

        /* post-open hook */
        FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.afterOpen(this),
            (feature, ex) -> logger.error("{}: feature {} after-open failure because of {}", this,
                feature.getClass().getName(), ex.getMessage(), ex));

        return success.get();
    }

    @FunctionalInterface
    private interface PredicateWithEx<T> {
        boolean test(T value) throws InterruptedException;
    }

    @Override
    public synchronized boolean stop() {

        /* policy-engine dispatch pre stop hook */
        if (FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.beforeStop(this),
            (feature, ex) -> logger.error("{}: feature {} before-stop failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex))) {
            return true;
        }

        /* stop regardless of the lock state */

        if (!this.alive) {
            return true;
        }

        this.alive = false;

        AtomicReference<Boolean> success = new AtomicReference<>(true);

        attempt(success, getControllerFactory().inventory(),
            PolicyController::stop,
            (item, ex) -> {
                logger.error("{}: cannot stop policy-controller {} because of {}", this, item,
                                ex.getMessage(), ex);
                success.set(false);
            });

        /* Stop Policy Engine owned (unmanaged) sources */
        attempt(success, this.sources,
            TopicSource::stop,
            (item, ex) -> logger.error("{}: cannot stop topic-source {} because of {}", this, item,
                            ex.getMessage(), ex));

        /* Stop Policy Engine owned (unmanaged) sinks */
        attempt(success, this.sinks,
            TopicSink::stop,
            (item, ex) -> logger.error("{}: cannot stop topic-sink {} because of {}", this, item,
                            ex.getMessage(), ex));

        /* stop all managed topics sources and sinks */
        if (!getTopicEndpointManager().stop()) {
            success.set(false);
        }

        /* stop all managed and unmanaged http servers */
        attempt(success,
            Stream.concat(getServletFactory().inventory().stream(), this.httpServers.stream())
                    .collect(Collectors.toList()),
            HttpServletServer::stop,
            (item, ex) -> logger.error("{}: cannot stop http-server {} because of {}", this, item,
                ex.getMessage(), ex));

        /* stop all managed http clients */
        attempt(success,
            getHttpClientFactory().inventory(),
            HttpClient::stop,
            (item, ex) -> logger.error("{}: cannot stop http-client {} because of {}", this, item,
                ex.getMessage(), ex));

        try {
            success.compareAndSet(true, this.lockManager.stop());
        } catch (final RuntimeException e) {
            logger.warn("{}: cannot stop lock manager because of {}", this, e.getMessage(), e);
            success.set(false);
        }

        // stop JMX?

        /* policy-engine dispatch post stop hook */
        FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.afterStop(this),
            (feature, ex) -> logger.error("{}: feature {} after-stop failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex));

        return success.get();
    }

    @Override
    public synchronized void shutdown() {

        /*
         * shutdown activity even when underlying subcomponents (features, controllers, topics, etc
         * ..) are stuck
         */

        var exitThread = makeShutdownThread();
        exitThread.start();

        /* policy-engine dispatch pre shutdown hook */
        if (FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.beforeShutdown(this),
            (feature, ex) -> logger.error("{}: feature {} before-shutdown failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex))) {
            return;
        }

        this.alive = false;

        /* Shutdown Policy Engine owned (unmanaged) sources */
        applyAll(this.sources,
            TopicSource::shutdown,
            (item, ex) -> logger.error("{}: cannot shutdown topic-source {} because of {}", this, item,
                            ex.getMessage(), ex));

        /* Shutdown Policy Engine owned (unmanaged) sinks */
        applyAll(this.sinks,
            TopicSink::shutdown,
            (item, ex) -> logger.error("{}: cannot shutdown topic-sink {} because of {}", this, item,
                            ex.getMessage(), ex));

        /* Shutdown managed resources */
        getControllerFactory().shutdown();
        getTopicEndpointManager().shutdown();
        getServletFactory().destroy();
        getHttpClientFactory().destroy();

        try {
            this.lockManager.shutdown();
        } catch (final RuntimeException e) {
            logger.warn("{}: cannot shutdown lock manager because of {}", this, e.getMessage(), e);
        }

        executorService.shutdownNow();

        // Stop the JMX listener

        stopPdpJmxListener();

        /* policy-engine dispatch post shutdown hook */
        FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.afterShutdown(this),
            (feature, ex) -> logger.error("{}: feature {} after-shutdown failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex));

        exitThread.interrupt();
        logger.info("{}: normal termination", this);
    }

    private <T> void attempt(AtomicReference<Boolean> success, List<T> items, PredicateWithEx<T> pred,
                    BiConsumer<T, Exception> handleEx) {

        for (T item : items) {
            try {
                if (!pred.test(item)) {
                    success.set(false);
                }

            } catch (InterruptedException ex) {
                handleEx.accept(item, ex);
                Thread.currentThread().interrupt();

            } catch (RuntimeException ex) {
                handleEx.accept(item, ex);
            }
        }
    }

    private <T> void applyAll(List<T> items, Consumer<T> function,
                    BiConsumer<T, Exception> handleEx) {

        for (T item : items) {
            try {
                function.accept(item);

            } catch (RuntimeException ex) {
                handleEx.accept(item, ex);
            }
        }
    }

    /**
     * Thread that shuts down http servers.
     */
    protected class ShutdownThread extends Thread {
        private static final long SHUTDOWN_MAX_GRACE_TIME = 30000L;

        @Override
        public void run() {
            try {
                doSleep(SHUTDOWN_MAX_GRACE_TIME);
                logger.warn("{}: abnormal termination - shutdown graceful time period expiration",
                        PolicyEngineManager.this);
            } catch (final InterruptedException e) {
                synchronized (PolicyEngineManager.this) {
                    /* courtesy to shutdown() to allow it to return */
                    Thread.currentThread().interrupt();
                }
                logger.info("{}: finishing a graceful shutdown ", PolicyEngineManager.this, e);
            } finally {
                /*
                 * shut down the Policy Engine owned http servers as the very last thing
                 */
                applyAll(PolicyEngineManager.this.getHttpServers(),
                    HttpServletServer::shutdown,
                    (item, ex) -> logger.error("{}: cannot shutdown http-server {} because of {}", this, item,
                                    ex.getMessage(), ex));

                logger.info("{}: exit", PolicyEngineManager.this);
                doExit(0);
            }
        }

        // these may be overridden by junit tests

        protected void doSleep(long sleepMs) throws InterruptedException {
            Thread.sleep(sleepMs);
        }

        protected void doExit(int code) {
            System.exit(code);
        }
    }

    @Override
    public synchronized boolean lock() {

        /* policy-engine dispatch pre lock hook */
        if (FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.beforeLock(this),
            (feature, ex) -> logger.error("{}: feature {} before-lock failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex))) {
            return true;
        }

        if (this.locked) {
            return true;
        }

        this.locked = true;

        var success = true;
        final List<PolicyController> controllers = getControllerFactory().inventory();
        for (final PolicyController controller : controllers) {
            try {
                success = controller.lock() && success;
            } catch (final Exception e) {
                logger.error("{}: cannot lock policy-controller {} because of {}", this, controller, e.getMessage(), e);
                success = false;
            }
        }

        success = getTopicEndpointManager().lock() && success;

        try {
            success = (this.lockManager == null || this.lockManager.lock()) && success;
        } catch (final RuntimeException e) {
            logger.warn("{}: cannot lock() lock manager because of {}", this, e.getMessage(), e);
            success = false;
        }

        /* policy-engine dispatch post lock hook */
        FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.afterLock(this),
            (feature, ex) -> logger.error("{}: feature {} after-lock failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex));

        return success;
    }

    @Override
    public synchronized boolean unlock() {

        /* policy-engine dispatch pre unlock hook */
        if (FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.beforeUnlock(this),
            (feature, ex) -> logger.error("{}: feature {} before-unlock failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex))) {
            return true;
        }

        if (!this.locked) {
            return true;
        }

        this.locked = false;

        boolean success;

        try {
            success = this.lockManager == null || this.lockManager.unlock();
        } catch (final RuntimeException e) {
            logger.warn("{}: cannot unlock() lock manager because of {}", this, e.getMessage(), e);
            success = false;
        }

        final List<PolicyController> controllers = getControllerFactory().inventory();
        for (final PolicyController controller : controllers) {
            try {
                success = controller.unlock() && success;
            } catch (final Exception e) {
                logger.error("{}: cannot unlock policy-controller {} because of {}", this, controller, e.getMessage(),
                        e);
                success = false;
            }
        }

        success = getTopicEndpointManager().unlock() && success;

        /* policy-engine dispatch after unlock hook */
        FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.afterUnlock(this),
            (feature, ex) -> logger.error("{}: feature {} after-unlock failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex));

        return success;
    }

    @Override
    public void removePolicyController(String name) {
        getControllerFactory().destroy(name);
    }

    @Override
    public void removePolicyController(PolicyController controller) {
        getControllerFactory().destroy(controller);
    }

    @GsonJsonIgnore
    @Override
    public List<PolicyController> getPolicyControllers() {
        return getControllerFactory().inventory();
    }

    @GsonJsonProperty("controllers")
    @Override
    public List<String> getPolicyControllerIds() {
        final List<String> controllerNames = new ArrayList<>();
        for (final PolicyController controller : getControllerFactory().inventory()) {
            controllerNames.add(controller.getName());
        }
        return controllerNames;
    }

    @Override
    @GsonJsonIgnore
    public Properties getProperties() {
        return this.properties;
    }

    @Override
    public List<String> getFeatures() {
        final List<String> features = new ArrayList<>();
        for (final PolicyEngineFeatureApi feature : getEngineProviders()) {
            features.add(feature.getName());
        }
        return features;
    }

    @GsonJsonIgnore
    @Override
    public List<PolicyEngineFeatureApi> getFeatureProviders() {
        return getEngineProviders();
    }

    @Override
    public PolicyEngineFeatureApi getFeatureProvider(String featureName) {
        if (featureName == null || featureName.isEmpty()) {
            throw new IllegalArgumentException("A feature name must be provided");
        }

        for (final PolicyEngineFeatureApi feature : getEngineProviders()) {
            if (feature.getName().equals(featureName)) {
                return feature;
            }
        }

        throw new IllegalArgumentException("Invalid Feature Name: " + featureName);
    }

    @Override
    public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
        /* policy-engine pre topic event hook */
        if (FeatureApiUtils.apply(getFeatureProviders(),
            feature -> feature.beforeOnTopicEvent(this, commType, topic, event),
            (feature, ex) -> logger.error(
                            "{}: feature {} beforeOnTopicEvent failure on event {} because of {}", this,
                            feature.getClass().getName(), event, ex.getMessage(), ex))) {
            return;
        }

        /* configuration request */
        PdpdConfiguration configuration = null;
        try {
            configuration = this.decoder.fromJson(event, PdpdConfiguration.class);
            this.configure(configuration);
        } catch (final Exception e) {
            logger.error("{}: configuration-error due to {} because of {}", this, event, e.getMessage(), e);
        }

        /* policy-engine after topic event hook */
        PdpdConfiguration configuration2 = configuration;
        FeatureApiUtils.apply(getFeatureProviders(),
            feature -> feature.afterOnTopicEvent(this, configuration2, commType, topic, event),
            (feature, ex) -> logger.error("{}: feature {} afterOnTopicEvent failure on event {} because of {}", this,
                            feature.getClass().getName(), event, ex.getMessage(), ex));
    }

    @Override
    public boolean deliver(String topic, Object event) {

        /*
         * Note this entry point is usually from the DRL
         */

        if (topic == null || topic.isEmpty()) {
            throw new IllegalArgumentException(INVALID_TOPIC_MSG);
        }

        if (event == null) {
            throw new IllegalArgumentException(INVALID_EVENT_MSG);
        }

        if (!this.isAlive()) {
            throw new IllegalStateException(ENGINE_STOPPED_MSG);
        }

        if (this.isLocked()) {
            throw new IllegalStateException(ENGINE_LOCKED_MSG);
        }

        final List<TopicSink> topicSinks = getTopicEndpointManager().getTopicSinks(topic);
        if (topicSinks == null || topicSinks.size() != 1) {
            throw new IllegalStateException("Cannot ensure correct delivery on topic " + topic + ": " + topicSinks);
        }

        return this.deliver(topicSinks.get(0).getTopicCommInfrastructure(), topic, event);
    }

    @Override
    public boolean deliver(String busType, String topic, Object event) {

        /*
         * Note this entry point is usually from the DRL (one of the reasons busType is String.
         */

        if (StringUtils.isBlank(busType)) {
            throw new IllegalArgumentException("Invalid Communication Infrastructure");
        }

        if (StringUtils.isBlank(topic)) {
            throw new IllegalArgumentException(INVALID_TOPIC_MSG);
        }

        if (event == null) {
            throw new IllegalArgumentException(INVALID_EVENT_MSG);
        }

        boolean valid = Stream.of(Topic.CommInfrastructure.values()).map(Enum::name)
                        .anyMatch(name -> name.equals(busType));

        if (!valid) {
            throw new IllegalArgumentException("Invalid Communication Infrastructure: " + busType);
        }


        if (!this.isAlive()) {
            throw new IllegalStateException(ENGINE_STOPPED_MSG);
        }

        if (this.isLocked()) {
            throw new IllegalStateException(ENGINE_LOCKED_MSG);
        }


        return this.deliver(Topic.CommInfrastructure.valueOf(busType), topic, event);
    }

    @Override
    public boolean deliver(Topic.CommInfrastructure busType, String topic, Object event) {

        if (topic == null || topic.isEmpty()) {
            throw new IllegalArgumentException(INVALID_TOPIC_MSG);
        }

        if (event == null) {
            throw new IllegalArgumentException(INVALID_EVENT_MSG);
        }

        if (!this.isAlive()) {
            throw new IllegalStateException(ENGINE_STOPPED_MSG);
        }

        if (this.isLocked()) {
            throw new IllegalStateException(ENGINE_LOCKED_MSG);
        }

        /*
         * Try to send through the controller, this is the preferred way, since it may want to apply
         * additional processing
         */
        try {
            var droolsController = getProtocolCoder().getDroolsController(topic, event);
            final PolicyController controller = getControllerFactory().get(droolsController);
            if (controller != null) {
                return controller.deliver(busType, topic, event);
            }
        } catch (final Exception e) {
            logger.warn("{}: cannot find policy-controller to deliver {} over {}:{} because of {}", this, event,
                    busType, topic, e.getMessage(), e);

            /* continue (try without routing through the controller) */
        }

        /*
         * cannot route through the controller, send directly through the topic sink
         */
        try {
            final String json = getProtocolCoder().encode(topic, event);
            return this.deliver(busType, topic, json);

        } catch (final Exception e) {
            logger.warn("{}: cannot deliver {} over {}:{}", this, event, busType, topic);
            throw e;
        }
    }

    @Override
    public boolean deliver(Topic.CommInfrastructure busType, String topic, String event) {

        if (topic == null || topic.isEmpty()) {
            throw new IllegalArgumentException(INVALID_TOPIC_MSG);
        }

        if (event == null || event.isEmpty()) {
            throw new IllegalArgumentException(INVALID_EVENT_MSG);
        }

        if (!this.isAlive()) {
            throw new IllegalStateException(ENGINE_STOPPED_MSG);
        }

        if (this.isLocked()) {
            throw new IllegalStateException(ENGINE_LOCKED_MSG);
        }

        try {
            var sink = getTopicEndpointManager().getTopicSink(busType, topic);

            if (sink == null) {
                throw new IllegalStateException("Inconsistent State: " + this);
            }

            return sink.send(event);

        } catch (final Exception e) {
            logger.warn("{}: cannot deliver {} over {}:{}", this, event, busType, topic);
            throw e;
        }
    }

    @Override
    public synchronized void activate() {

        /* policy-engine dispatch pre activate hook */
        if (FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.beforeActivate(this),
            (feature, ex) -> logger.error("{}: feature {} before-activate failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex))) {
            return;
        }

        // activate 'policy-management'
        for (final PolicyController policyController : this.getPolicyControllers()) {
            try {
                policyController.unlock();
                policyController.start();
            } catch (final Exception e) {
                logger.error("{}: cannot activate of policy-controller {} because of {}", this, policyController,
                        e.getMessage(), e);
            } catch (final LinkageError e) {
                logger.error("{}: cannot activate (rules compilation) of policy-controller {} because of {}", this,
                        policyController, e.getMessage(), e);
            }
        }

        this.unlock();

        /* policy-engine dispatch post activate hook */
        FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.afterActivate(this),
            (feature, ex) -> logger.error("{}: feature {} after-activate failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex));
    }

    @Override
    public synchronized void deactivate() {

        /* policy-engine dispatch pre deactivate hook */
        if (FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.beforeDeactivate(this),
            (feature, ex) -> logger.error("{}: feature {} before-deactivate failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex))) {
            return;
        }

        this.lock();

        for (final PolicyController policyController : this.getPolicyControllers()) {
            try {
                policyController.stop();
            } catch (final Exception | LinkageError e) {
                logger.error("{}: cannot deactivate (stop) policy-controller {} because of {}", this, policyController,
                        e.getMessage(), e);
            }
        }

        /* policy-engine dispatch post deactivate hook */
        FeatureApiUtils.apply(getEngineProviders(),
            feature -> feature.afterDeactivate(this),
            (feature, ex) -> logger.error("{}: feature {} after-deactivate failure because of {}", this,
                            feature.getClass().getName(), ex.getMessage(), ex));
    }

    @Override
    public Lock createLock(@NonNull String resourceId, @NonNull String ownerKey, int holdSec,
                    @NonNull LockCallback callback, boolean waitForLock) {

        if (holdSec < 0) {
            throw new IllegalArgumentException("holdSec is negative");
        }

        if (lockManager == null) {
            throw new IllegalStateException("lock manager has not been initialized");
        }

        return lockManager.createLock(resourceId, ownerKey, holdSec, callback, waitForLock);
    }

    private boolean controllerConfig(PdpdConfiguration config) {
        /* only this one supported for now */
        final List<ControllerConfiguration> configControllers = config.getControllers();
        if (configControllers == null || configControllers.isEmpty()) {
            logger.info("No controller configuration provided: {}", config);
            return false;
        }

        final List<PolicyController> policyControllers = this.updatePolicyControllers(config.getControllers());
        return (policyControllers != null && !policyControllers.isEmpty()
                        && policyControllers.size() == configControllers.size());
    }

    // these methods may be overridden by junit tests

    protected List<PolicyEngineFeatureApi> getEngineProviders() {
        return PolicyEngineFeatureApiConstants.getProviders().getList();
    }

    protected List<PolicyControllerFeatureApi> getControllerProviders() {
        return PolicyControllerFeatureApiConstants.getProviders().getList();
    }

    protected void globalInitContainer(String[] cliArgs) {
        PolicyContainer.globalInit(cliArgs);
    }

    protected TopicEndpoint getTopicEndpointManager() {
        return TopicEndpointManager.getManager();
    }

    protected HttpServletServerFactory getServletFactory() {
        return HttpServletServerFactoryInstance.getServerFactory();
    }

    protected HttpClientFactory getHttpClientFactory() {
        return HttpClientFactoryInstance.getClientFactory();
    }

    protected PolicyControllerFactory getControllerFactory() {
        return PolicyControllerConstants.getFactory();
    }

    protected void startPdpJmxListener() {
        PdpJmxListener.start();
    }

    protected void stopPdpJmxListener() {
        PdpJmxListener.stop();
    }

    protected Thread makeShutdownThread() {
        return new ShutdownThread();
    }

    protected EventProtocolCoder getProtocolCoder() {
        return EventProtocolCoderConstants.getManager();
    }

    protected SystemPersistence getPersistenceManager() {
        return SystemPersistenceConstants.getManager();
    }

    protected PolicyEngine getPolicyEngine() {
        return PolicyEngineConstants.getManager();
    }

    protected ScheduledExecutorService makeScheduledExecutor(int nthreads) {
        var exsvc = new ScheduledThreadPoolExecutor(nthreads);
        exsvc.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
        exsvc.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
        exsvc.setRemoveOnCancelPolicy(true);

        return exsvc;
    }
}