aboutsummaryrefslogtreecommitdiffstats
path: root/policy-management/src/main/java/org/openecomp/policy/drools/system/PolicyEngine.java
blob: 33f2a098342c38f1798ba0bf8fc5666f828f5211 (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
/*-
 * ============LICENSE_START=======================================================
 * policy-management
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * 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.openecomp.policy.drools.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.openecomp.policy.common.logging.eelf.MessageCodes;
import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
import org.openecomp.policy.common.logging.flexlogger.Logger;
import org.openecomp.policy.drools.controller.DroolsController;
import org.openecomp.policy.drools.core.FeatureAPI;
import org.openecomp.policy.drools.core.jmx.PdpJmxListener;
import org.openecomp.policy.drools.event.comm.Topic;
import org.openecomp.policy.drools.event.comm.Topic.CommInfrastructure;
import org.openecomp.policy.drools.event.comm.TopicEndpoint;
import org.openecomp.policy.drools.event.comm.TopicListener;
import org.openecomp.policy.drools.event.comm.TopicSink;
import org.openecomp.policy.drools.event.comm.TopicSource;
import org.openecomp.policy.drools.http.server.HttpServletServer;
import org.openecomp.policy.drools.persistence.SystemPersistence;
import org.openecomp.policy.drools.properties.Lockable;
import org.openecomp.policy.drools.properties.PolicyProperties;
import org.openecomp.policy.drools.properties.Startable;
import org.openecomp.policy.drools.protocol.coders.EventProtocolCoder;
import org.openecomp.policy.drools.protocol.configuration.ControllerConfiguration;
import org.openecomp.policy.drools.protocol.configuration.PdpdConfiguration;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Policy Engine, the top abstraction for the Drools PDP Policy Engine.
 * It abstracts away a Drools PDP Engine from management purposes.
 * This is the best place to looking at the code from a top down approach. 
 * Other managed entities can be obtained from the PolicyEngine, hierarchically. 
 * <br>
 * PolicyEngine 1 --- * PolicyController 1 --- 1 DroolsController 1 --- 1 PolicyContainer 1 --- * PolicySession
 * <br>
 * PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicReader 1 --- 1 UebTopicReader
 * <br>
 * PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicReader 1 --- 1 DmaapTopicReader
 * <br>
 * PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicWriter 1 --- 1 DmaapTopicWriter
 * <br>
 * PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicReader 1 --- 1 RestTopicReader
 * <br>
 * PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicWriter 1 --- 1 RestTopicWriter
 * <br>
 * PolicyEngine 1 --- 1 ManagementServer
 */
public interface PolicyEngine extends Startable, Lockable, TopicListener {
	
	/**
	 * Default Config Server Port
	 */
	public static final int CONFIG_SERVER_DEFAULT_PORT = 9696;
	
	/**
	 * Default Config Server Hostname
	 */
	public static final String CONFIG_SERVER_DEFAULT_HOST = "localhost";
	
	/**
	 * configure the policy engine according to the given properties
	 * 
	 * @param properties Policy Engine properties
	 * @throws IllegalArgumentException when invalid or insufficient 
	 *         properties are provided
	 */
	public void configure(Properties properties)  throws IllegalArgumentException;

	/**
	 * registers a new Policy Controller with the Policy Engine
	 * initialized per properties.
	 * 
	 * @param controller name
	 * @param properties properties to initialize the Policy Controller
	 * @throws IllegalArgumentException when invalid or insufficient 
	 *         properties are provided
	 * @throws IllegalStateException when the engine is in a state where
	 *         this operation is not permitted.
	 * @return the newly instantiated Policy Controller
	 */
	public PolicyController createPolicyController(String name, Properties properties)
		throws IllegalArgumentException, IllegalStateException;
	
	/**
	 * updates the Policy Engine with the given configuration
	 * 
	 * @param configuration the configuration
	 * @return success or failure
	 * @throws IllegalArgumentException if invalid argument provided
	 * @throws IllegalStateException if the system is in an invalid state
	 */
	public boolean configure(PdpdConfiguration configuration)
		throws IllegalArgumentException, IllegalStateException;
	
	/**
	 * updates a set of Policy Controllers with configuration information
	 * 
	 * @param configuration
	 * @return
	 * @throws IllegalArgumentException
	 * @throws IllegalStateException
	 */
	public List<PolicyController> updatePolicyControllers(List<ControllerConfiguration> configuration)
		throws IllegalArgumentException, IllegalStateException;
	
	/**
	 * updates an already existing Policy Controller with configuration information
	 * 
	 * @param configuration configuration
	 * 
	 * @return the updated Policy Controller
	 * @throws IllegalArgumentException in the configuration is invalid
	 * @throws IllegalStateException if the controller is in a bad state
	 * @throws Exception any other reason
	 */
	public PolicyController updatePolicyController(ControllerConfiguration configuration)
		throws Exception;

	/**
	 * removes the Policy Controller identified by its name from the Policy Engine
	 * 
	 * @param name name of the Policy Controller
	 * @return the removed Policy Controller
	 */
	public void removePolicyController(String name);
	
	/**
	 * removes a Policy Controller from the Policy Engine
	 * @param controller the Policy Controller to remove from the Policy Engine
	 */
	public void removePolicyController(PolicyController controller);

	/**
	 * returns a list of the available Policy Controllers
	 * 
	 * @return list of Policy Controllers
	 */
	public List<PolicyController> getPolicyControllers();
	
	/**
	 * get unmanaged sources
	 * 
	 * @return unmanaged sources
	 */
	public List<TopicSource> getSources();
	
	/**
	 * get unmanaged sinks
	 * 
	 * @return unmanaged sinks
	 */
	public List<TopicSink> getSinks();
	
	/**
	 * get unmmanaged http servers list
	 * @return http servers
	 */
	public List<HttpServletServer> getHttpServers();
	
	/**
	 * get properties configuration
	 * 
	 * @return properties objects
	 */
	public Properties getProperties();
	
	/**
	 * Attempts the dispatching of an "event" object
	 * 
	 * @param topic topic
	 * @param event the event object to send
	 * 
	 * @return true if successful, false if a failure has occurred.
	 * @throws IllegalArgumentException when invalid or insufficient 
	 *         properties are provided
	 * @throws IllegalStateException when the engine is in a state where
	 *         this operation is not permitted (ie. locked or stopped).
	 */
	public boolean deliver(String topic, Object event)
			throws IllegalArgumentException, IllegalStateException;
	
	/**
	 * Attempts the dispatching of an "event" object over communication 
	 * infrastructure "busType"
	 * 
	 * @param eventBus Communication infrastructure identifier
	 * @param topic topic
	 * @param event the event object to send
	 * 
	 * @return true if successful, false if a failure has occurred.
	 * @throws IllegalArgumentException when invalid or insufficient 
	 *         properties are provided
	 * @throws IllegalStateException when the engine is in a state where
	 *         this operation is not permitted (ie. locked or stopped).
	 * @throws UnsupportedOperationException when the engine cannot deliver due
	 *         to the functionality missing (ie. communication infrastructure
	 *         not supported.
	 */
	public boolean deliver(String busType, String topic, Object event)
			throws IllegalArgumentException, IllegalStateException, 
			       UnsupportedOperationException;
	
	/**
	 * Attempts the dispatching of an "event" object over communication 
	 * infrastructure "busType"
	 * 
	 * @param eventBus Communication infrastructure enum
	 * @param topic topic
	 * @param event the event object to send
	 * 
	 * @return true if successful, false if a failure has occurred.
	 * @throws IllegalArgumentException when invalid or insufficient 
	 *         properties are provided
	 * @throws IllegalStateException when the engine is in a state where
	 *         this operation is not permitted (ie. locked or stopped).
	 * @throws UnsupportedOperationException when the engine cannot deliver due
	 *         to the functionality missing (ie. communication infrastructure
	 *         not supported.
	 */
	public boolean deliver(CommInfrastructure busType, String topic, Object event)
			throws IllegalArgumentException, IllegalStateException, 
			       UnsupportedOperationException;
	
	/**
	 * Attempts delivering of an String over communication 
	 * infrastructure "busType"
	 * 
	 * @param eventBus Communication infrastructure identifier
	 * @param topic topic
	 * @param event the event object to send
	 * 
	 * @return true if successful, false if a failure has occurred.
	 * @throws IllegalArgumentException when invalid or insufficient 
	 *         properties are provided
	 * @throws IllegalStateException when the engine is in a state where
	 *         this operation is not permitted (ie. locked or stopped).
	 * @throws UnsupportedOperationException when the engine cannot deliver due
	 *         to the functionality missing (ie. communication infrastructure
	 *         not supported.
	 */
	public boolean deliver(CommInfrastructure busType, String topic, 
			               String event)
			throws IllegalArgumentException, IllegalStateException, 
			       UnsupportedOperationException;
	
	/**
	 * Invoked when the host goes into the active state.
	 */
	public void activate();

	/**
	 * Invoked when the host goes into the standby state.
	 */
	public void deactivate();

	/**
	 * get policy controller names
	 * 
	 * @return list of controller names
	 */
	public List<String> getControllers();
	
	/**
	 * Policy Engine Manager
	 */
	public final static PolicyEngine manager = new PolicyEngineManager();
}

/**
 * Policy Engine Manager Implementation
 */
class PolicyEngineManager implements PolicyEngine {
	/**
	 * logger
	 */
	private static Logger  logger = FlexLogger.getLogger(PolicyEngineManager.class);  	
	
	/**
	 * Is the Policy Engine running?
	 */
	protected boolean alive = false;
	
	/**
	 * Is the engine locked? 
	 */
	protected boolean locked = false;	
	
	/**
	 * Properties used to initialize the engine
	 */
	protected Properties properties;
	
	/**
	 * Policy Engine Sources
	 */
	protected List<? extends TopicSource> sources = new ArrayList<>();
	
	/**
	 * Policy Engine Sinks
	 */
	protected List<? extends TopicSink> sinks = new ArrayList<>();
	
	/**
	 * Policy Engine HTTP Servers
	 */
	protected List<HttpServletServer> httpServers = new ArrayList<HttpServletServer>();
	
	protected Gson decoder = new GsonBuilder().disableHtmlEscaping().create();

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void configure(Properties properties) throws IllegalArgumentException {
		
		if (properties == null) {
			logger.warn("No properties provided");
			throw new IllegalArgumentException("No properties provided");
		}
		
		this.properties = properties;
		
		try {
			this.sources = TopicEndpoint.manager.addTopicSources(properties);
			for (TopicSource source: this.sources) {
				source.register(this);
			}
		} catch (Exception e) {
			logger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyEngine", "configure");
		}
		
		try {
			this.sinks = TopicEndpoint.manager.addTopicSinks(properties);
		} catch (IllegalArgumentException e) {
			logger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyEngine", "configure");
		}
		
		try {
			this.httpServers = HttpServletServer.factory.build(properties);
		} catch (IllegalArgumentException e) {
			logger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyEngine", "configure");
		}
		
		return;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public PolicyController createPolicyController(String name, Properties properties) 
			throws IllegalArgumentException, IllegalStateException {
		
		// check if a PROPERTY_CONTROLLER_NAME property is present
		// if so, override the given name
		
		String propertyControllerName = properties.getProperty(PolicyProperties.PROPERTY_CONTROLLER_NAME);
		if (propertyControllerName != null && !propertyControllerName.isEmpty())  {
			if (!propertyControllerName.equals(name)) {
				throw new IllegalStateException("Proposed name (" + name + 
						                        ") and properties name (" + propertyControllerName + 
						                        ") don't match");
			}
			name = propertyControllerName;
		}
		
		// feature hook
		for (FeatureAPI feature : FeatureAPI.impl.getList()) {
			feature.beforeCreateController(name, properties);
		}
		
		PolicyController controller = PolicyController.factory.build(name, properties);	
		if (this.isLocked())
			controller.lock();
		
		// feature hook
		for (FeatureAPI feature : FeatureAPI.impl.getList()) {
			//  NOTE: this should change to the actual controller object
			feature.afterCreateController(name);
		}
		
		return controller;
	}
	

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean configure(PdpdConfiguration config) throws IllegalArgumentException, IllegalStateException {
	
		if (config == null)
			throw new IllegalArgumentException("No configuration provided");
		
		String entity = config.getEntity();
		
		switch (entity) {
		case PdpdConfiguration.CONFIG_ENTITY_CONTROLLER:
			/* only this one supported for now */
			List<ControllerConfiguration> configControllers = config.getControllers();
			if (configControllers == null || configControllers.isEmpty()) {
				if (logger.isInfoEnabled())
					logger.info("No controller configuration provided: " + config);
				return false;
			}
			List<PolicyController> policyControllers = this.updatePolicyControllers(config.getControllers());
			if (policyControllers == null || policyControllers.isEmpty())
				return false;
			else if (policyControllers.size() == configControllers.size())
				return true;
			
			return false;
		default:
			String msg = "Configuration Entity is not supported: " + entity;
			logger.warn(msg);
			throw new IllegalArgumentException(msg);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<PolicyController> updatePolicyControllers(List<ControllerConfiguration> configControllers)
			throws IllegalArgumentException, IllegalStateException {
		
		List<PolicyController> policyControllers = new ArrayList<PolicyController>();
		if (configControllers == null || configControllers.isEmpty()) {
			if (logger.isInfoEnabled())
				logger.info("No controller configuration provided: " + configControllers);
			return policyControllers;
		}
		
		for (ControllerConfiguration configController: configControllers) {
			try {
				PolicyController policyController = this.updatePolicyController(configController);
				policyControllers.add(policyController);
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyEngine", "updatePolicyControllers");
			}
		}
		
		return policyControllers;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public PolicyController updatePolicyController(ControllerConfiguration configController) 
		   throws Exception {
		
		if (configController == null) 
			throw new IllegalArgumentException("No controller configuration has been provided");
		
		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");
		}
		
		PolicyController policyController = null;
		try {		
			String operation = configController.getOperation();
			if (operation == null || operation.isEmpty()) {
				logger.warn("operation must be provided");
				throw new IllegalArgumentException("operation must be provided");
			}
			
			try {
				policyController = PolicyController.factory.get(controllerName);
			} catch (IllegalArgumentException e) {
				// not found
				logger.warn("Policy Controller " + controllerName + " not found");
			}
			
			if (policyController == null) {
				
				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 " + controllerName + " does not exist.  " +
				            "Attempting recovery from disk");	
				
				Properties properties = 
						SystemPersistence.manager.getControllerProperties(controllerName);
				
				/* 
				 * returned properties cannot be null (per implementation) 
				 * assert (properties != null)
				 */
				
				if (properties == null) {
					throw new IllegalArgumentException(controllerName + " is invalid");
				}
				
				logger.warn("controller " + controllerName + " being recovered. " +
			                "Reset controller's bad maven coordinates to brainless");
				
				/* 
				 * try to bring up bad controller in brainless mode,
				 * after having it working, apply the new create/update operation.
				 */
				properties.setProperty(PolicyProperties.RULES_GROUPID, DroolsController.NO_GROUP_ID);
				properties.setProperty(PolicyProperties.RULES_ARTIFACTID, DroolsController.NO_ARTIFACT_ID);
				properties.setProperty(PolicyProperties.RULES_VERSION, DroolsController.NO_VERSION);
				
				policyController = PolicyEngine.manager.createPolicyController(controllerName, properties);
				
				/* fall through to do brain update operation*/
			}
			
			switch (operation) {
			case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_CREATE:
				PolicyController.factory.patch(policyController, configController.getDrools());
				break;
			case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_UPDATE:
				policyController.unlock();
				PolicyController.factory.patch(policyController, configController.getDrools());
				break;
			case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_LOCK:
				policyController.lock();
				break;
			case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_UNLOCK:
				policyController.unlock();
				break;
			default:
				String msg = "Controller Operation Configuration is not supported: " + 
		                     operation + " for " + controllerName;
				logger.warn(msg);
				throw new IllegalArgumentException(msg);
			}
			
			return policyController;
		} catch (Exception e) {
			logger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyEngine", "updatePolicyController " + e.getMessage());
			throw e;
		} catch (LinkageError e) {
			logger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyEngine", "updatePolicyController " + e.getMessage());
			throw new IllegalStateException(e);
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean start() throws IllegalStateException {
		
		if (this.locked) {
			throw new IllegalStateException("Engine is locked");
		}
		
		// Features hook
		for (FeatureAPI feature : FeatureAPI.impl.getList()) {
			feature.beforeStartEngine();
		}
		
		synchronized(this) {
			this.alive = true;
		}
		
		boolean success = true;

		/* Start Policy Engine exclusively-owned (unmanaged) http servers */
		
		for (HttpServletServer httpServer: this.httpServers) {
			try {
				if (!httpServer.start())
					success = false;
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, httpServer.toString(), this.toString());
			}
		}
		/* Start Policy Engine exclusively-owned (unmanaged) sources */
		
		for (TopicSource source: this.sources) {
			try {
				if (!source.start())
					success = false;
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, source.toString(), this.toString());
			}
		}
		
		/* Start Policy Engine owned (unmanaged) sinks */
		
		for (TopicSink sink: this.sinks) {
			try {
				if (!sink.start())
					success = false;
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, sink.toString(), this.toString());
			}
		}
		
		/* Start Policy Controllers */
		
		List<PolicyController> controllers = PolicyController.factory.inventory();
		for (PolicyController controller : controllers) {
			try {
				if (!controller.start())
					success = false;
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, controller.toString(), this.toString());
				success = false;
			}
		}
		
		/* Start managed Topic Endpoints */
		
		try {
			if (!TopicEndpoint.manager.start())
				success = false;			
		} catch (IllegalStateException e) {
			String msg = "Topic Endpoint Manager is in an invalid state: " + e.getMessage() + " : " + this;
			logger.warn(msg);			
		}
		
		
		// Start the JMX listener
		
		PdpJmxListener.start();
		
		// Features hook
		for (FeatureAPI feature : FeatureAPI.impl.getList()) {
			feature.afterStartEngine();
		}

		return success;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean stop() {
		
		/* stop regardless of the lock state */
		
		synchronized(this) {
			if (!this.alive)
				return true;
			
			this.alive = false;			
		}
		
		boolean success = true;
		List<PolicyController> controllers = PolicyController.factory.inventory();
		for (PolicyController controller : controllers) {
			try {
				if (!controller.stop())
					success = false;
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, controller.toString(), this.toString());
				success = false;
			}
		}
		
		/* Stop Policy Engine owned (unmanaged) sources */
		for (TopicSource source: this.sources) {
			try {
				if (!source.stop())
					success = false;
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, source.toString(), this.toString());
			}
		}
		
		/* Stop Policy Engine owned (unmanaged) sinks */
		for (TopicSink sink: this.sinks) {
			try {
				if (!sink.stop())
					success = false;
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, sink.toString(), this.toString());
			}
		}
		
		/* stop all managed topics sources and sinks */
		if (!TopicEndpoint.manager.stop())
			success = false;
		
		/* stop all unmanaged http servers */
		for (HttpServletServer httpServer: this.httpServers) {
			try {
				if (!httpServer.stop())
					success = false;
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, httpServer.toString(), this.toString());
			}
		}		
		
		return success;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void shutdown() throws IllegalStateException {

		synchronized(this) {
			this.alive = false;			
		}
		
		// feature hook reporting that the Policy Engine is being shut down		
		for (FeatureAPI feature : FeatureAPI.impl.getList()) {
			feature.beforeShutdownEngine();
		}
		
		/* Shutdown Policy Engine owned (unmanaged) sources */
		for (TopicSource source: this.sources) {
			try {
				source.shutdown();
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, source.toString(), this.toString());
			}
		}
		
		/* Shutdown Policy Engine owned (unmanaged) sinks */
		for (TopicSink sink: this.sinks) {
			try {
				sink.shutdown();
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, sink.toString(), this.toString());
			}
		}
		
		/* Shutdown managed resources */
		PolicyController.factory.shutdown();
		TopicEndpoint.manager.shutdown();
		HttpServletServer.factory.destroy();
		
		// Stop the JMX listener
		
		PdpJmxListener.stop();
		
		// feature hook reporting that the Policy Engine has being shut down		
		for (FeatureAPI feature : FeatureAPI.impl.getList()) {
			feature.afterShutdownEngine();
		}
		
		new Thread(new Runnable() {
		    @Override
		    public void run() {
		    	try {
					Thread.sleep(5000L);
				} catch (InterruptedException e) {
					logger.warn("InterruptedException while shutting down management server: " +  this.toString());
				}		    	
				
				/* shutdown all unmanaged http servers */
				for (HttpServletServer httpServer: getHttpServers()) {
					try {
						httpServer.shutdown();
					} catch (Exception e) {
						logger.error(MessageCodes.EXCEPTION_ERROR, e, httpServer.toString(), this.toString());
					}
				} 
		    	
		    	try {
					Thread.sleep(5000L);
				} catch (InterruptedException e) {
					logger.warn("InterruptedException while shutting down management server: " +  this.toString());
				}
		    	
		    	System.exit(0);
		    }		    
		}).start();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean isAlive() {
		return this.alive;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean lock() {
		
		synchronized(this) {
			if (this.locked)
				return true;
			
			this.locked = true;			
		}
		
		boolean success = true;
		List<PolicyController> controllers = PolicyController.factory.inventory();
		for (PolicyController controller : controllers) {
			try {
				success = controller.lock() && success;
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, controller.toString(), this.toString());
				success = false;
			}
		}
		
		success = TopicEndpoint.manager.lock();		
		return success;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean unlock() {
		synchronized(this) {
			if (!this.locked)
				return true;
			
			this.locked = false;			
		}
		
		boolean success = true;
		List<PolicyController> controllers = PolicyController.factory.inventory();
		for (PolicyController controller : controllers) {
			try {
				success = controller.unlock() && success;
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, controller.toString(), this.toString());
				success = false;
			}
		}
		
		success = TopicEndpoint.manager.unlock();		
		return success;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean isLocked() {
		return this.locked;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void removePolicyController(String name) {
		PolicyController.factory.destroy(name);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void removePolicyController(PolicyController controller) {
		PolicyController.factory.destroy(controller);
	}

	/**
	 * {@inheritDoc}
	 */
	@JsonIgnore
	@Override
	public List<PolicyController> getPolicyControllers() {
		return PolicyController.factory.inventory();
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<String> getControllers() {
		List<String> controllerNames = new ArrayList<String>();
		for (PolicyController controller: PolicyController.factory.inventory()) {
			controllerNames.add(controller.getName());
		}
		return controllerNames;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public Properties getProperties() {
		return this.properties;
	}
	

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<TopicSource> getSources() {
		return (List<TopicSource>) this.sources;
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<TopicSink> getSinks() {
		return (List<TopicSink>) this.sinks;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<HttpServletServer> getHttpServers() {
		return this.httpServers;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onTopicEvent(CommInfrastructure commType, String topic, String event) {
		/* configuration request */
		try {
			PdpdConfiguration configuration = this.decoder.fromJson(event, PdpdConfiguration.class);
			this.configure(configuration);
		} catch (Exception e) {
			logger.error(MessageCodes.EXCEPTION_ERROR, e, "CONFIGURATION ERROR IN PDP-D POLICY ENGINE: "+ event + ":" + e.getMessage() + ":" + this);
		}
		
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean deliver(String topic, Object event) 
			throws IllegalArgumentException, IllegalStateException {
		
		/*
		 * Note this entry point is usually from the DRL
		 */
		
		if (topic == null || topic.isEmpty())
			throw new IllegalArgumentException("Invalid Topic");
		
		if (event == null)
			throw new IllegalArgumentException("Invalid Event");
			
		if (!this.isAlive())
			throw new IllegalStateException("Policy Engine is stopped");
		
		if (this.isLocked())
			throw new IllegalStateException("Policy Engine is locked");
		
		List<? extends TopicSink> sinks = 
				TopicEndpoint.manager.getTopicSinks(topic);
		if (sinks == null || sinks.isEmpty() || sinks.size() > 1)
			throw new IllegalStateException
				("Cannot ensure correct delivery on topic " + topic + ": " + sinks);		

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

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean deliver(String busType, String topic, Object event) 
			throws IllegalArgumentException, IllegalStateException,
		       UnsupportedOperationException {
		
		/*
		 * Note this entry point is usually from the DRL (one of the reasons
		 * busType is String.
		 */
		
		if (busType == null || busType.isEmpty())
			throw new IllegalArgumentException
				("Invalid Communication Infrastructure");
		
		if (topic == null || topic.isEmpty())
			throw new IllegalArgumentException("Invalid Topic");
		
		if (event == null)
			throw new IllegalArgumentException("Invalid Event");
		
		boolean valid = false;
		for (Topic.CommInfrastructure comm: Topic.CommInfrastructure.values()) {
			if (comm.name().equals(busType)) {
				valid = true;
			}
		}
		
		if (!valid)
			throw new IllegalArgumentException
				("Invalid Communication Infrastructure: " + busType);
		
		
		if (!this.isAlive())
			throw new IllegalStateException("Policy Engine is stopped");
		
		if (this.isLocked())
			throw new IllegalStateException("Policy Engine is locked");
		

		return this.deliver(Topic.CommInfrastructure.valueOf(busType), 
				            topic, event);
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean deliver(Topic.CommInfrastructure busType, 
			               String topic, Object event) 
		throws IllegalArgumentException, IllegalStateException,
		       UnsupportedOperationException {
		
		if (topic == null || topic.isEmpty())
			throw new IllegalArgumentException("Invalid Topic");
		
		if (event == null)
			throw new IllegalArgumentException("Invalid Event");
		
		if (!this.isAlive())
			throw new IllegalStateException("Policy Engine is stopped");
		
		if (this.isLocked())
			throw new IllegalStateException("Policy Engine is locked");
		
		/* Try to send through the controller, this is the
		 * preferred way, since it may want to apply additional
		 * processing
		 */
		try {
			DroolsController droolsController = 
					EventProtocolCoder.manager.getDroolsController(topic, event);
			PolicyController controller = PolicyController.factory.get(droolsController);
			if (controller != null)
				return controller.deliver(busType, topic, event);
		} catch (Exception e) {
			logger.warn(MessageCodes.EXCEPTION_ERROR, e, 
					          busType + ":" + topic + " :" + event, this.toString());
			/* continue (try without routing through the controller) */
		}
		
		/*
		 * cannot route through the controller, send directly through
		 * the topic sink
		 */
		try {			
			String json = EventProtocolCoder.manager.encode(topic, event);
			return this.deliver(busType, topic, json);

		} catch (Exception e) {
			logger.warn(MessageCodes.EXCEPTION_ERROR, e, 
			          busType + ":" + topic + " :" + event, this.toString());
			throw e;
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean deliver(Topic.CommInfrastructure busType, 
			               String topic, String event) 
		throws IllegalArgumentException, IllegalStateException,
		       UnsupportedOperationException {
		
		if (topic == null || topic.isEmpty())
			throw new IllegalArgumentException("Invalid Topic");
		
		if (event == null || event.isEmpty())
			throw new IllegalArgumentException("Invalid Event");
		
		if (!this.isAlive())
			throw new IllegalStateException("Policy Engine is stopped");
		
		if (this.isLocked())
			throw new IllegalStateException("Policy Engine is locked");
		
		try {
			TopicSink sink = 
					TopicEndpoint.manager.getTopicSink
						(busType, topic);
			
			if (sink == null)
				throw new IllegalStateException("Inconsistent State: " + this);
			
			return sink.send(event);

		} catch (Exception e) {
			logger.warn(MessageCodes.EXCEPTION_ERROR, e, 
			          busType + ":" + topic + " :" + event, this.toString());
			throw e;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public synchronized void activate() {

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

	/**
	 * {@inheritDoc}
	 */
	@Override
	public synchronized void deactivate() {
		
		this.lock();
		
		for (PolicyController policyController : getPolicyControllers()) {
			try { 
				policyController.stop();
			} catch (Exception e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyEngine.deactivate: cannot stop " + 
		                     policyController + " because of " + e.getMessage());
			} catch (LinkageError e) {
				logger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyEngine.deactivate: cannot start " + 
			                 policyController + " because of " + e.getMessage());
			}
		}	  
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("PolicyEngineManager [alive=").append(alive).append(", locked=").append(locked).append("]");
		return builder.toString();
	}
	
}