d1e6336b085f24813d4369098b81ec5659ae89bd
[policy/drools-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * policy-persistence
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.policy.drools.controller.test;
22
23 import static org.junit.Assert.assertTrue;
24
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.util.ArrayList;
28 import java.util.Date;
29 import java.util.Properties;
30
31 import javax.persistence.EntityManager;
32 import javax.persistence.EntityManagerFactory;
33 import javax.persistence.EntityTransaction;
34 import javax.persistence.Persistence;
35
36 import org.apache.commons.lang3.time.DateUtils;
37 import org.junit.After;
38 import org.junit.AfterClass;
39 import org.junit.Before;
40 import org.junit.BeforeClass;
41 import org.junit.Ignore;
42 import org.junit.Test;
43 import org.openecomp.policy.common.im.AdministrativeStateException;
44 import org.openecomp.policy.common.im.IntegrityMonitor;
45 import org.openecomp.policy.common.im.StandbyStatusException;
46 import org.openecomp.policy.common.im.StateManagement;
47 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
48 import org.openecomp.policy.common.logging.flexlogger.Logger;
49 import org.openecomp.policy.drools.core.DroolsPDPIntegrityMonitor;
50 import org.openecomp.policy.drools.core.IntegrityMonitorProperties;
51 import org.openecomp.policy.drools.core.PolicyContainer;
52 import org.openecomp.policy.drools.im.PMStandbyStateChangeNotifier;
53 import org.openecomp.policy.drools.persistence.DroolsPdp;
54 import org.openecomp.policy.drools.persistence.DroolsPdpEntity;
55 import org.openecomp.policy.drools.persistence.DroolsPdpImpl;
56 import org.openecomp.policy.drools.persistence.DroolsPdpsConnector;
57 import org.openecomp.policy.drools.persistence.DroolsPdpsElectionHandler;
58 import org.openecomp.policy.drools.persistence.DroolsPersistenceProperties;
59 import org.openecomp.policy.drools.persistence.JpaDroolsPdpsConnector;
60 import org.openecomp.policy.drools.persistence.XacmlPersistenceProperties;
61 import org.openecomp.policy.drools.system.Main;
62 import org.openecomp.policy.drools.system.PolicyEngine;
63
64 /*
65  * All JUnits are designed to run in the local development environment
66  * where they have write privileges and can execute time-sensitive
67  * tasks.
68  * 
69  * These tests can be run as JUnits, but there is some issue with running them
70  * as part of a "mvn install" build.  Also, they take a very long time to run
71  * due to many real time breaks.  Consequently, they are marked as @Ignore and
72  * only run from the desktop.
73  * 
74  */
75 public class StandbyStateManagementTest {
76         private static Logger  logger = FlexLogger.getLogger(StandbyStateManagementTest.class);
77         /*
78          * Currently, the DroolsPdpsElectionHandler.DesignationWaiter is invoked every ten seconds, starting 
79          * at ten seconds after the minute boundary (e.g. 13:05:10). So, an 80 second sleep should be 
80          * sufficient to ensure that we wait for the DesignationWaiter to do its job, before 
81          * checking the results. 
82          */
83         long sleepTime = 80000;
84         
85         /*
86          * DroolsPdpsElectionHandler runs every ten seconds, so a 15 second sleep should be 
87          * plenty to ensure it has time to re-promote this PDP.
88          */
89         long electionWaitSleepTime = 15000;
90         
91         /*
92          * Sleep 5 seconds after each test to allow interrupt (shutdown) recovery.
93          */
94         long interruptRecoveryTime = 5000;
95         
96         private static EntityManagerFactory emfx;
97         private static EntityManagerFactory emfd;
98         private static EntityManager emx;
99         private static EntityManager emd;
100         private static EntityTransaction et;
101
102         /*
103          * See the IntegrityMonitor.getJmxUrl() method for the rationale behind this jmx related processing.
104          */
105         @BeforeClass
106         public static void setUpClass() throws Exception {
107                 
108                 String userDir = System.getProperty("user.dir");
109                 logger.debug("setUpClass: userDir=" + userDir);
110                 System.setProperty("com.sun.management.jmxremote.port", "9980");
111                 System.setProperty("com.sun.management.jmxremote.authenticate","false");
112                                 
113                 // Make sure path to config directory is set correctly in PolicyContainer.main
114                 // Also make sure we ignore HTTP server failures resulting from port conflicts.
115                 PolicyContainer.isUnitTesting = true;
116                 
117         }
118
119         @AfterClass
120         public static void tearDownClass() throws Exception {
121         }
122
123         @Before
124         public void setUp() throws Exception {
125                 //Create teh data access for xaml db
126                 Properties xacmlPersistenceProperties = new Properties();
127                 xacmlPersistenceProperties.load(new FileInputStream(new File(
128                                 "src/test/server/config/xacmlPersistence.properties")));
129
130                 emfx = Persistence.createEntityManagerFactory("junitXacmlPU", xacmlPersistenceProperties);
131
132                 // Create an entity manager to use the DB
133                 emx = emfx.createEntityManager();
134                 
135                 //Create the data access for drools db
136                 Properties droolsPersistenceProperties = new Properties();
137                 droolsPersistenceProperties.load(new FileInputStream(new File(
138                                 "src/test/server/config/droolsPersistence.properties")));
139
140                 emfd = Persistence.createEntityManagerFactory("junitDroolsPU", droolsPersistenceProperties);
141
142                 // Create an entity manager to use the DB
143                 emd = emfd.createEntityManager();
144         }
145
146         @After
147         public void tearDown() throws Exception {
148                                 
149         }
150         
151         public void cleanXacmlDb(){
152                 et = emx.getTransaction();
153                 
154                 et.begin();
155                 // Make sure we leave the DB clean
156                 emx.createQuery("DELETE FROM StateManagementEntity").executeUpdate();
157                 emx.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate();
158                 emx.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate();
159                 emx.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate();
160                 emx.flush();
161                 et.commit();
162         }
163         
164         public void cleanDroolsDb(){
165                 et = emd.getTransaction();
166                 
167                 et.begin();
168                 // Make sure we leave the DB clean
169                 emd.createQuery("DELETE FROM DroolsPdpEntity").executeUpdate();
170                 emd.createQuery("DELETE FROM DroolsSessionEntity").executeUpdate();
171                 emd.createQuery("DELETE FROM SessionInfo").executeUpdate();
172                 emd.createQuery("DELETE FROM WorkItemInfo").executeUpdate();
173                 emd.createQuery("DELETE FROM IntegrityAuditEntity").executeUpdate();
174                 emd.flush();
175                 et.commit();
176         }
177         
178         /*
179          * These JUnit tests must be run in an eclipse environment by right-clicking
180          * StandbyStateManagementTest and selecting "Run As" -> "JUnit Test". If you 
181          * run them as part of mvn install, they will fail with an error "JUnit The 
182          * forked VM terminated without saying properly goodbye"
183          */
184         @Ignore
185         @Test
186         public void runAllTests() throws Exception {
187                 //testColdStandby();
188                 //testHotStandby1();
189                 //testHotStandby2();
190                 //testLocking1();
191                 //testLocking2();
192                 //testSanitizeDesignatedList();
193                 //testComputeMostRecentPrimary();
194                 //testComputeDesignatedPdp();
195                 testPMStandbyStateChangeNotifier();
196         }
197         
198         private void testPMStandbyStateChangeNotifier() throws Exception {
199                 logger.debug("\n\ntestPMStandbyStateChangeNotifier: Entering\n\n");
200                 cleanXacmlDb();
201
202                 logger.debug("testPMStandbyStateChangeNotifier: Reading IntegrityMonitorProperties");
203
204                 Properties integrityMonitorProperties = new Properties();
205                 integrityMonitorProperties.load(new FileInputStream(new File(
206                                 "src/test/server/config/IntegrityMonitor.properties")));
207                 IntegrityMonitorProperties.initProperties(integrityMonitorProperties);
208
209                 logger.debug("testPMStandbyStateChangeNotifier: Reading droolsPersistenceProperties");
210                 Properties droolsPersistenceProperties = new Properties();
211                 droolsPersistenceProperties.load(new FileInputStream(new File(
212                                 "src/test/server/config/droolsPersistence.properties")));
213                 DroolsPersistenceProperties.initProperties(droolsPersistenceProperties);
214
215                 logger.debug("testPMStandbyStateChangeNotifier: Reading xacmlPersistenceProperties");
216
217                 Properties xacmlPersistenceProperties = new Properties();
218                 xacmlPersistenceProperties.load(new FileInputStream(new File(
219                                 "src/test/server/config/xacmlPersistence.properties")));
220                 XacmlPersistenceProperties.initProperties(xacmlPersistenceProperties);
221
222                 logger.debug("testPMStandbyStateChangeNotifier: Creating emfXacml");
223                 EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory(
224                                 "junitXacmlPU", xacmlPersistenceProperties);
225                 
226                 //Now get the StateManagement instance so we can register our observer
227                 StateManagement sm = new StateManagement(emfXacml, "pdp1");
228
229                 //Create an instance of the Observer
230                 PMStandbyStateChangeNotifier pmNotifier = new PMStandbyStateChangeNotifier();
231
232                 //Register the PMStandbyStateChangeNotifier Observer
233                 sm.addObserver(pmNotifier);
234
235                 //At this point the standbystatus = 'null'
236                 sm.lock();
237                 assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.NULL_VALUE));
238
239                 sm.unlock();
240                 assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.NULL_VALUE));
241
242                 //Adding standbystatus=hotstandby
243                 sm.demote();
244                 System.out.println(pmNotifier.getPreviousStandbyStatus());
245                 assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY));
246
247                 //Now making standbystatus=coldstandby
248                 sm.lock();
249                 assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY));
250
251                 //standbystatus = hotstandby
252                 sm.unlock();
253                 assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY));
254
255                 //standbystatus = providingservice
256                 sm.promote();
257                 //The previousStandbyStatus is not updated until after the delay activation expires
258                 assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY));
259
260                 //Sleep long enough for the delayActivationTimer to run
261                 Thread.sleep(5000);
262                 assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.PROVIDING_SERVICE));
263
264                 //standbystatus = providingservice
265                 sm.promote();
266                 assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.PROVIDING_SERVICE));
267                 
268                 //standbystatus = coldstandby
269                 sm.lock();
270                 assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY));
271
272                 //standbystatus = hotstandby
273                 sm.unlock();
274                 assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY));
275
276                 //standbystatus = hotstandby
277                 sm.demote();
278                 assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY));
279                 
280         }
281         
282         
283         //@Ignore
284         //@Test
285         public void testSanitizeDesignatedList() throws Exception {
286
287                 logger.debug("\n\ntestSanitizeDesignatedList: Entering\n\n");
288                 
289                 /*
290                  * Get a DroolsPdpsConnector
291                  */
292                 logger.debug("testSanitizeDesignatedList: Reading droolsPersistenceProperties");
293                 Properties droolsPersistenceProperties = new Properties();
294                 droolsPersistenceProperties.load(new FileInputStream(new File(
295                                 "src/test/server/config/droolsPersistence.properties")));
296                 DroolsPersistenceProperties.initProperties(droolsPersistenceProperties);
297
298                 logger.debug("testSanitizeDesignatedList: Creating emfDrools");
299                 EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory(
300                                 "junitDroolsPU", droolsPersistenceProperties);
301                 
302                 DroolsPdpsConnector droolsPdpsConnector = new JpaDroolsPdpsConnector(emfDrools);
303                 
304                 /*
305                  * Create 4 pdpd all not designated
306                  */
307                 DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, new Date());
308                 DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, new Date());
309                 DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, new Date());
310                 DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, new Date());
311                 
312                 ArrayList<DroolsPdp> listOfDesignated = new ArrayList<DroolsPdp>();
313                 listOfDesignated.add(pdp1);
314                 listOfDesignated.add(pdp2);
315                 listOfDesignated.add(pdp3);
316                 listOfDesignated.add(pdp4);
317                 
318                 DroolsPDPIntegrityMonitor droolsPDPIntegrityMonitor;
319                 try{
320                         droolsPDPIntegrityMonitor = DroolsPDPIntegrityMonitor.init("src/test/server/config");
321                 }catch(Exception e){
322                         //If it already exists, just get it
323                         droolsPDPIntegrityMonitor = DroolsPDPIntegrityMonitor.getInstance();
324                 }
325                 DroolsPdpsElectionHandler droolsPdpsElectionHandler =  new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1, droolsPDPIntegrityMonitor);
326                 
327                 listOfDesignated = droolsPdpsElectionHandler.santizeDesignatedList(listOfDesignated);
328                 
329                 logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size = " + listOfDesignated.size() + "\n\n");
330                 
331                 assertTrue(listOfDesignated.size()==4);
332                 
333                 /*
334                  * Now make 2 designated
335                  */
336                 pdp1.setDesignated(true);
337                 pdp2.setDesignated(true);
338                 
339                 listOfDesignated = droolsPdpsElectionHandler.santizeDesignatedList(listOfDesignated);
340                 
341                 logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size after 2 designated = " + listOfDesignated.size() + "\n\n");
342                 
343                 assertTrue(listOfDesignated.size()==2);
344                 assertTrue(listOfDesignated.contains(pdp1));
345                 assertTrue(listOfDesignated.contains(pdp2));
346                 
347                 /*
348                  * Now all are designated.  But, we have to add back the previously non-designated nodes
349                  */
350                 pdp3.setDesignated(true);
351                 pdp4.setDesignated(true);
352                 listOfDesignated.add(pdp3);
353                 listOfDesignated.add(pdp4);
354                 
355                 listOfDesignated = droolsPdpsElectionHandler.santizeDesignatedList(listOfDesignated);
356                 
357                 logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size after all designated = " + listOfDesignated.size() + "\n\n");
358                 
359                 assertTrue(listOfDesignated.size()==4);
360                 
361         }
362         
363         //@Ignore
364         //@Test
365         public void testComputeMostRecentPrimary() throws Exception {
366
367                 logger.debug("\n\ntestComputeMostRecentPrimary: Entering\n\n");
368                 
369                 /*
370                  * Get a DroolsPdpsConnector
371                  */
372                 logger.debug("testComputeMostRecentPrimary: Reading droolsPersistenceProperties");
373                 Properties droolsPersistenceProperties = new Properties();
374                 droolsPersistenceProperties.load(new FileInputStream(new File(
375                                 "src/test/server/config/droolsPersistence.properties")));
376                 DroolsPersistenceProperties.initProperties(droolsPersistenceProperties);
377
378                 logger.debug("testComputeMostRecentPrimary: Creating emfDrools");
379                 EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory(
380                                 "junitDroolsPU", droolsPersistenceProperties);
381                 
382                 DroolsPdpsConnector droolsPdpsConnector = new JpaDroolsPdpsConnector(emfDrools);
383                 
384                 /*
385                  * Create 4 pdpd all not designated
386                  */
387                 long designatedDateMS = new Date().getTime();
388                 DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, new Date());
389                 pdp1.setDesignatedDate(new Date(designatedDateMS - 2));
390                 
391                 DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, new Date());
392                 //oldest
393                 pdp2.setDesignatedDate(new Date(designatedDateMS - 3));
394                 
395                 DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, new Date());
396                 pdp3.setDesignatedDate(new Date(designatedDateMS - 1));
397
398                 DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, new Date());
399                 //most recent
400                 pdp4.setDesignatedDate(new Date(designatedDateMS));
401                 
402                 ArrayList<DroolsPdp> listOfAllPdps = new ArrayList<DroolsPdp>();
403                 listOfAllPdps.add(pdp1);
404                 listOfAllPdps.add(pdp2);
405                 listOfAllPdps.add(pdp3);
406                 listOfAllPdps.add(pdp4);
407                                 
408                 
409                 ArrayList<DroolsPdp> listOfDesignated = new ArrayList<DroolsPdp>();
410                 listOfDesignated.add(pdp1);
411                 listOfDesignated.add(pdp2);
412                 listOfDesignated.add(pdp3);
413                 listOfDesignated.add(pdp4);
414                 
415                 
416                 /*
417                  * Because the way we sanitize the listOfDesignated, it will always contain all hot standby 
418                  * or all designated members.
419                  */
420                 DroolsPDPIntegrityMonitor droolsPDPIntegrityMonitor;
421                 try{
422                         droolsPDPIntegrityMonitor = DroolsPDPIntegrityMonitor.init("src/test/server/config");
423                 }catch(Exception e){
424                         //If it already exists, just get it
425                         droolsPDPIntegrityMonitor = DroolsPDPIntegrityMonitor.getInstance();
426                 }
427                 DroolsPdpsElectionHandler droolsPdpsElectionHandler =  new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1, droolsPDPIntegrityMonitor);
428         
429                 DroolsPdp mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated);
430                 
431                 logger.debug("\n\ntestComputeMostRecentPrimary: mostRecentPrimary.getPdpId() = " + mostRecentPrimary.getPdpId() + "\n\n");
432                 
433                 /*
434                  * If all of the pdps are included in the listOfDesignated and none are designated, it will choose 
435                  * the one which has the most recent designated date.
436                  */
437                 assertTrue(mostRecentPrimary.getPdpId().equals("pdp4"));
438                 
439                 /*
440                  * Now let's designate all of those on the listOfDesignated.  It will choose the first one designated
441                  */
442                 pdp1.setDesignated(true);
443                 pdp2.setDesignated(true);
444                 pdp3.setDesignated(true);
445                 pdp4.setDesignated(true);
446                 
447                 mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated);
448                 
449                 logger.debug("\n\ntestComputeMostRecentPrimary: All designated all on list, mostRecentPrimary.getPdpId() = " + mostRecentPrimary.getPdpId() + "\n\n");
450                 
451                 /*
452                  * If all of the pdps are included in the listOfDesignated and all are designated, it will choose 
453                  * the one which was designated first
454                  */
455                 assertTrue(mostRecentPrimary.getPdpId().equals("pdp2"));
456                 
457                 /*
458                  * Now we will designate only 2 and put just them in the listOfDesignated.  The algorithm will now
459                  * look for the most recently designated pdp which is not currently designated.
460                  */
461                 pdp3.setDesignated(false);
462                 pdp4.setDesignated(false);
463                 
464                 listOfDesignated.remove(pdp3);
465                 listOfDesignated.remove(pdp4);
466                 
467                 mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated);
468                 
469                 logger.debug("\n\ntestComputeMostRecentPrimary: mostRecentPrimary.getPdpId() = " + mostRecentPrimary.getPdpId() + "\n\n");
470                 
471                 assertTrue(mostRecentPrimary.getPdpId().equals("pdp4"));
472                 
473                 
474                 /*
475                  * Now we will have none designated and put two of them in the listOfDesignated.  The algorithm will now
476                  * look for the most recently designated pdp regardless of whether it is currently marked as designated.
477                  */
478                 pdp1.setDesignated(false);
479                 pdp2.setDesignated(false);
480                 
481                 mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated);
482                 
483                 logger.debug("\n\ntestComputeMostRecentPrimary: 2 on list mostRecentPrimary.getPdpId() = " + mostRecentPrimary.getPdpId() + "\n\n");
484                 
485                 assertTrue(mostRecentPrimary.getPdpId().equals("pdp4"));
486                 
487                 /*
488                  * If we have only one pdp on in the listOfDesignated, the most recently designated pdp will be chosen, regardless
489                  * of its designation status
490                  */
491                 listOfDesignated.remove(pdp1);
492                 
493                 mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated);
494                 
495                 logger.debug("\n\ntestComputeMostRecentPrimary: 1 on list mostRecentPrimary.getPdpId() = " + mostRecentPrimary.getPdpId() + "\n\n");
496                 
497                 assertTrue(mostRecentPrimary.getPdpId().equals("pdp4"));
498                 
499                 /*
500                  * Finally, if none are on the listOfDesignated, it will again choose the most recently designated pdp.
501                  */
502                 listOfDesignated.remove(pdp2);
503
504                 mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated);
505                 
506                 logger.debug("\n\ntestComputeMostRecentPrimary: 0 on list mostRecentPrimary.getPdpId() = " + mostRecentPrimary.getPdpId() + "\n\n");
507                 
508                 assertTrue(mostRecentPrimary.getPdpId().equals("pdp4"));
509                 
510         }
511         
512         //@Ignore
513         //@Test
514         public void testComputeDesignatedPdp() throws Exception{
515                 
516                 logger.debug("\n\ntestComputeDesignatedPdp: Entering\n\n");
517                 
518                 /*
519                  * Get a DroolsPdpsConnector
520                  */
521                 logger.debug("testComputeDesignatedPdp: Reading droolsPersistenceProperties");
522                 Properties droolsPersistenceProperties = new Properties();
523                 droolsPersistenceProperties.load(new FileInputStream(new File(
524                                 "src/test/server/config/droolsPersistence.properties")));
525                 DroolsPersistenceProperties.initProperties(droolsPersistenceProperties);
526
527                 logger.debug("testComputeDesignatedPdp: Creating emfDrools");
528                 EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory(
529                                 "junitDroolsPU", droolsPersistenceProperties);
530                 
531                 DroolsPdpsConnector droolsPdpsConnector = new JpaDroolsPdpsConnector(emfDrools);
532                 
533                 /*
534                  * Create 4 pdpd all not designated.  Two on site1. Two on site2
535                  */
536                 long designatedDateMS = new Date().getTime();
537                 DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, new Date());
538                 pdp1.setDesignatedDate(new Date(designatedDateMS - 2));
539                 pdp1.setSiteName("site1");
540                 
541                 DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, new Date());
542                 pdp2.setDesignatedDate(new Date(designatedDateMS - 3));
543                 pdp2.setSiteName("site1");
544
545                 //oldest                
546                 DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, new Date());
547                 pdp3.setDesignatedDate(new Date(designatedDateMS - 4));
548                 pdp3.setSiteName("site2");
549                 
550                 DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, new Date());
551                 //most recent
552                 pdp4.setDesignatedDate(new Date(designatedDateMS));
553                 pdp4.setSiteName("site2");
554                 
555                 ArrayList<DroolsPdp> listOfAllPdps = new ArrayList<DroolsPdp>();
556                 listOfAllPdps.add(pdp1);
557                 listOfAllPdps.add(pdp2);
558                 listOfAllPdps.add(pdp3);
559                 listOfAllPdps.add(pdp4);
560                                 
561                 
562                 ArrayList<DroolsPdp> listOfDesignated = new ArrayList<DroolsPdp>();
563                 
564                 /*
565                  * We will first test an empty listOfDesignated. As we know from the previous JUnit,
566                  * the pdp with the most designated date will be chosen for mostRecentPrimary  
567                  */
568                 
569                 DroolsPDPIntegrityMonitor droolsPDPIntegrityMonitor;
570                 try{
571                         droolsPDPIntegrityMonitor = DroolsPDPIntegrityMonitor.init("src/test/server/config");
572                 }catch(Exception e){
573                         //If it already exists, just get it
574                         droolsPDPIntegrityMonitor = DroolsPDPIntegrityMonitor.getInstance();
575                 }
576                 DroolsPdpsElectionHandler droolsPdpsElectionHandler =  new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1, droolsPDPIntegrityMonitor);
577                 
578                 DroolsPdp mostRecentPrimary = pdp4;
579         
580                 DroolsPdp designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary);
581                 
582                 /*
583                  * The designatedPdp should be null
584                  */
585                 assertTrue(designatedPdp==null);
586                 
587                 /*
588                  * Now let's try having only one pdp in listOfDesignated, but not in the same site as the most recent primary
589                  */
590                 
591                 listOfDesignated.add(pdp2);
592                 
593                 designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary);
594                 
595                 /*
596                  * Now the designatedPdp should be the one and only selection in the listOfDesignated
597                  */
598                 assertTrue(designatedPdp.getPdpId().equals(pdp2.getPdpId()));
599                 
600                 /*
601                  * Now let's put 2 pdps in the listOfDesignated, neither in the same site as the mostRecentPrimary
602                  */
603                 listOfDesignated.add(pdp1);
604                 
605                 designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary);
606                 
607                 /*
608                  * The designatedPdp should now be the one with the lowest lexiographic score - pdp1
609                  */
610                 assertTrue(designatedPdp.getPdpId().equals(pdp1.getPdpId()));
611                 
612                 /*
613                  * Finally, we will have 2 pdps in the listOfDesignated, one in the same site with the mostRecentPrimary
614                  */
615                 listOfDesignated.remove(pdp1);
616                 listOfDesignated.add(pdp3);
617                 
618                 designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary);
619                 
620                 /*
621                  * The designatedPdp should now be the one on the same site as the mostRecentPrimary
622                  */
623                 assertTrue(designatedPdp.getPdpId().equals(pdp3.getPdpId()));
624         }
625         
626         
627         //@Ignore
628         //@Test
629         public void testColdStandby() throws Exception {
630
631                 logger.debug("\n\ntestColdStandby: Entering\n\n");
632                 cleanXacmlDb();
633                 cleanDroolsDb();
634
635                 logger.debug("testColdStandby: Reading IntegrityMonitorProperties");
636                 Properties integrityMonitorProperties = new Properties();
637                 integrityMonitorProperties.load(new FileInputStream(new File(
638                                 "src/test/server/config/IntegrityMonitor.properties")));
639                 IntegrityMonitorProperties.initProperties(integrityMonitorProperties);
640                 String thisPdpId = IntegrityMonitorProperties
641                                 .getProperty(IntegrityMonitorProperties.PDP_INSTANCE_ID);
642
643                 logger.debug("testColdStandby: Reading xacmlPersistenceProperties");
644                 Properties xacmlPersistenceProperties = new Properties();
645                 xacmlPersistenceProperties.load(new FileInputStream(new File(
646                                 "src/test/server/config/xacmlPersistence.properties")));
647                 XacmlPersistenceProperties.initProperties(xacmlPersistenceProperties);
648                 
649                 logger.debug("testColdStandby: Creating emfXacml");
650                 EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory(
651                                 "junitXacmlPU", xacmlPersistenceProperties);
652                 
653                 logger.debug("testColdStandby: Reading droolsPersistenceProperties");
654                 Properties droolsPersistenceProperties = new Properties();
655                 droolsPersistenceProperties.load(new FileInputStream(new File(
656                                 "src/test/server/config/droolsPersistence.properties")));
657                 DroolsPersistenceProperties.initProperties(droolsPersistenceProperties);
658
659                 logger.debug("testColdStandby: Creating emfDrools");
660                 EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory(
661                                 "junitDroolsPU", droolsPersistenceProperties);
662                 
663                 DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools);
664                 
665                 logger.debug("testColdStandby: Cleaning up tables");
666                 conn.deleteAllSessions();
667                 conn.deleteAllPdps();
668         
669                 logger.debug("testColdStandby: Inserting PDP=" + thisPdpId + " as designated");
670                 DroolsPdp pdp = new DroolsPdpImpl(thisPdpId, true, 4, new Date());
671                 conn.insertPdp(pdp);
672                 DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId);
673                 logger.debug("testColdStandby: After insertion, DESIGNATED="
674                                 + droolsPdpEntity.isDesignated() + " for PDP=" + thisPdpId);
675                 assertTrue(droolsPdpEntity.isDesignated() == true);
676
677                 /*
678                  * When the Standby Status changes (from providingservice) to hotstandby
679                  * or coldstandby,the Active/Standby selection algorithm must stand down
680                  * if thePDP-D is currently the lead/active node and allow another PDP-D
681                  * to take over.
682                  * 
683                  * It must also call lock on all engines in the engine management.
684                  * 
685                  * Yes, this is kludgy, but we have a chicken and egg problem here: we
686                  * need a StateManagement object to invoke the
687                  * deleteAllStateManagementEntities method.
688                  */
689                 logger.debug("testColdStandby: Instantiating stateManagement object");
690                 StateManagement sm = new StateManagement(emfXacml, "dummy");
691                 sm.deleteAllStateManagementEntities();
692                 sm = new StateManagement(emfXacml, thisPdpId);
693                 PMStandbyStateChangeNotifier pmStandbyStateChangeNotifier = new PMStandbyStateChangeNotifier();
694                 sm.addObserver(pmStandbyStateChangeNotifier);
695                 
696                 // Artificially putting a PDP into service is really a two step process, 1)
697                 // inserting it as designated and 2) promoting it so that its standbyStatus
698                 // is providing service.
699                 
700                 logger.debug("testColdStandby: Running policy-management.Main class");
701                 PolicyManagementRunner policyManagementRunner = new PolicyManagementRunner();
702                 policyManagementRunner.start();
703                 
704                 logger.debug("testColdStandby: Runner started; Sleeping "
705                                 + interruptRecoveryTime + "ms before promoting PDP="
706                                 + thisPdpId);
707                 Thread.sleep(interruptRecoveryTime);
708
709                 logger.debug("testColdStandby: Promoting PDP=" + thisPdpId);
710                 sm.promote();           
711                 
712                 String standbyStatus = sm.getStandbyStatus(thisPdpId);
713                 logger.debug("testColdStandby: Before locking, PDP=" + thisPdpId + " has standbyStatus="
714                                 + standbyStatus);
715                 
716                 logger.debug("testColdStandby: Locking sm");
717                 sm.lock();
718                 
719                 Thread.sleep(interruptRecoveryTime);
720                 /*
721                  * Verify that the PDP is no longer designated.
722                  */
723                 droolsPdpEntity = conn.getPdp(thisPdpId);
724                 logger.debug("testColdStandby: After lock sm.lock() invoked, DESIGNATED="
725                                 + droolsPdpEntity.isDesignated() + " for PDP=" + thisPdpId);
726                 assertTrue(droolsPdpEntity.isDesignated() == false);
727                 
728                 logger.debug("testColdStandby: Stopping policyManagementRunner");
729                 //policyManagementRunner.stopRunner();
730         
731                 logger.debug("\n\ntestColdStandby: Exiting\n\n");
732                 Thread.sleep(interruptRecoveryTime);
733
734         }
735         
736         /*
737          * Tests hot standby when there is only one PDP.
738          */
739         //@Ignore
740         //@Test
741         public void testHotStandby1() throws Exception {
742         
743                 logger.debug("\n\ntestHotStandby1: Entering\n\n");
744                 cleanXacmlDb();
745                 cleanDroolsDb();
746                 
747                 logger.debug("testHotStandby1: Reading IntegrityMonitorProperties");
748                 Properties integrityMonitorProperties = new Properties();
749                 integrityMonitorProperties.load(new FileInputStream(new File(
750                                 "src/test/server/config/IntegrityMonitor.properties")));
751                 IntegrityMonitorProperties.initProperties(integrityMonitorProperties);
752                 String thisPdpId = IntegrityMonitorProperties
753                                 .getProperty(IntegrityMonitorProperties.PDP_INSTANCE_ID);
754                 
755                 logger.debug("testHotStandby1: Reading xacmlPersistenceProperties");
756                 Properties xacmlPersistenceProperties = new Properties();
757                 xacmlPersistenceProperties.load(new FileInputStream(new File(
758                                 "src/test/server/config/xacmlPersistence.properties")));
759                 XacmlPersistenceProperties.initProperties(xacmlPersistenceProperties);
760                 
761                 logger.debug("testHotStandby1: Creating emfXacml");
762                 EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory(
763                                 "junitXacmlPU", xacmlPersistenceProperties);
764                 
765                 logger.debug("testHotStandby1: Reading droolsPersistenceProperties");
766                 Properties droolsPersistenceProperties = new Properties();
767                 droolsPersistenceProperties.load(new FileInputStream(new File(
768                                 "src/test/server/config/droolsPersistence.properties")));
769                 DroolsPersistenceProperties.initProperties(droolsPersistenceProperties);
770
771                 logger.debug("testHotStandby1: Creating emfDrools");
772                 EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory(
773                                 "junitDroolsPU", droolsPersistenceProperties);
774                 
775                 DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools);
776                 
777                 logger.debug("testHotStandby1: Cleaning up tables");
778                 conn.deleteAllSessions();
779                 conn.deleteAllPdps();
780                                         
781                 /*
782                  * Insert this PDP as not designated.  Initial standby state will be 
783                  * either null or cold standby.   Demoting should transit state to
784                  * hot standby.
785                  */
786                 logger.debug("testHotStandby1: Inserting PDP=" + thisPdpId + " as not designated");
787                 Date yesterday = DateUtils.addDays(new Date(), -1);
788                 DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday);
789                 conn.insertPdp(pdp);
790                 DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId);
791                 logger.debug("testHotStandby1: After insertion, PDP=" + thisPdpId + " has DESIGNATED="
792                                 + droolsPdpEntity.isDesignated());
793                 assertTrue(droolsPdpEntity.isDesignated() == false);
794                 
795                 logger.debug("testHotStandby1: Instantiating stateManagement object");
796                 StateManagement sm = new StateManagement(emfXacml, "dummy");
797                 sm.deleteAllStateManagementEntities();
798                 sm = new StateManagement(emfXacml, thisPdpId);
799                 PMStandbyStateChangeNotifier pmStandbyStateChangeNotifier = new PMStandbyStateChangeNotifier();
800                 sm.addObserver(pmStandbyStateChangeNotifier);
801
802                 logger.debug("testHotStandby1: Demoting PDP=" + thisPdpId);
803                 // demoting should cause state to transit to hotstandby
804                 sm.demote();
805                 
806                 logger.debug("testHotStandby1: Running policy-management.Main class");
807                 PolicyManagementRunner policyManagementRunner = new PolicyManagementRunner();
808                 policyManagementRunner.start();
809                                 
810                 logger.debug("testHotStandby1: Sleeping "
811                                 + sleepTime
812                                 + "ms, to allow JpaDroolsPdpsConnector time to check droolspdpentity table");
813                 Thread.sleep(sleepTime);
814                 
815                 /*
816                  * Verify that this formerly un-designated PDP in HOT_STANDBY is now designated and providing service.
817                  */
818                 droolsPdpEntity = conn.getPdp(thisPdpId);
819                 logger.debug("testHotStandby1: After sm.demote() invoked, DESIGNATED="
820                                 + droolsPdpEntity.isDesignated() + " for PDP=" + thisPdpId);
821                 assertTrue(droolsPdpEntity.isDesignated() == true);
822                 String standbyStatus = sm.getStandbyStatus(thisPdpId);
823                 logger.debug("testHotStandby1: After demotion, PDP=" + thisPdpId + " has standbyStatus="
824                                 + standbyStatus);
825                 assertTrue(standbyStatus != null  &&  standbyStatus.equals(StateManagement.PROVIDING_SERVICE));
826                                 
827                 logger.debug("testHotStandby1: Stopping policyManagementRunner");
828                 //policyManagementRunner.stopRunner();          
829         
830                 logger.debug("\n\ntestHotStandby1: Exiting\n\n");
831                 Thread.sleep(interruptRecoveryTime);
832
833         }
834
835         /*
836          * Tests hot standby when two PDPs are involved.
837          */
838         //@Ignore
839         //@Test
840         public void testHotStandby2() throws Exception {
841
842                 logger.info("\n\ntestHotStandby2: Entering\n\n");
843                 cleanXacmlDb();
844                 cleanDroolsDb();
845                 
846                 logger.info("testHotStandby2: Reading IntegrityMonitorProperties");
847                 Properties integrityMonitorProperties = new Properties();
848                 integrityMonitorProperties.load(new FileInputStream(new File(
849                                 "src/test/server/config/IntegrityMonitor.properties")));
850                 IntegrityMonitorProperties.initProperties(integrityMonitorProperties);
851                 String thisPdpId = IntegrityMonitorProperties
852                                 .getProperty(IntegrityMonitorProperties.PDP_INSTANCE_ID);
853                 
854                 logger.info("testHotStandby2: Reading xacmlPersistenceProperties");
855                 Properties xacmlPersistenceProperties = new Properties();
856                 xacmlPersistenceProperties.load(new FileInputStream(new File(
857                                 "src/test/server/config/xacmlPersistence.properties")));
858                 XacmlPersistenceProperties.initProperties(xacmlPersistenceProperties);
859                 
860                 logger.info("testHotStandby2: Creating emfXacml");
861                 EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory(
862                                 "junitXacmlPU", xacmlPersistenceProperties);
863                 
864                 logger.info("testHotStandby2: Reading droolsPersistenceProperties");
865                 Properties droolsPersistenceProperties = new Properties();
866                 droolsPersistenceProperties.load(new FileInputStream(new File(
867                                 "src/test/server/config/droolsPersistence.properties")));
868                 DroolsPersistenceProperties.initProperties(droolsPersistenceProperties);
869
870                 logger.info("testHotStandby2: Creating emfDrools");
871                 EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory(
872                                 "junitDroolsPU", droolsPersistenceProperties);
873                 
874                 DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools);
875                 
876                 logger.info("testHotStandby2: Cleaning up tables");
877                 conn.deleteAllSessions();
878                 conn.deleteAllPdps();
879                 
880                 /*
881                  * Insert a PDP that's designated but not current.
882                  */
883                 String activePdpId = "pdp2";
884                 logger.info("testHotStandby2: Inserting PDP=" + activePdpId + " as stale, designated PDP");
885                 Date yesterday = DateUtils.addDays(new Date(), -1);
886                 DroolsPdp pdp = new DroolsPdpImpl(activePdpId, true, 4, yesterday);
887                 conn.insertPdp(pdp);
888                 DroolsPdpEntity droolsPdpEntity = conn.getPdp(activePdpId);
889                 logger.info("testHotStandby2: After insertion, PDP=" + activePdpId + ", which is not current, has DESIGNATED="
890                                 + droolsPdpEntity.isDesignated());
891                 assertTrue(droolsPdpEntity.isDesignated() == true);
892                 
893                 /*
894                  * Promote the designated PDP.
895                  * 
896                  * We have a chicken and egg problem here: we need a StateManagement
897                  * object to invoke the deleteAllStateManagementEntities method.
898                  */
899                 logger.info("testHotStandby2: Promoting PDP=" + activePdpId);
900                 StateManagement sm = new StateManagement(emfXacml, "dummy");
901                 sm.deleteAllStateManagementEntities();
902                 sm = new StateManagement(emfXacml, activePdpId);//pdp2
903                 PMStandbyStateChangeNotifier pmStandbyStateChangeNotifier = new PMStandbyStateChangeNotifier();
904                 sm.addObserver(pmStandbyStateChangeNotifier);
905                 
906                 // Artificially putting a PDP into service is really a two step process, 1)
907                 // inserting it as designated and 2) promoting it so that its standbyStatus
908                 // is providing service.
909                                 
910                 /*
911                  * Insert this PDP as not designated.  Initial standby state will be 
912                  * either null or cold standby.   Demoting should transit state to
913                  * hot standby.
914                  */
915                 logger.info("testHotStandby2: Inserting PDP=" + thisPdpId + " as not designated");
916                 pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday);
917                 conn.insertPdp(pdp);
918                 droolsPdpEntity = conn.getPdp(thisPdpId);
919                 logger.info("testHotStandby2: After insertion, PDP=" + thisPdpId + " has DESIGNATED="
920                                 + droolsPdpEntity.isDesignated());
921                 assertTrue(droolsPdpEntity.isDesignated() == false);
922                 
923                 logger.info("testHotStandby2: Demoting PDP=" + thisPdpId);//pdp1
924                 StateManagement sm2 = new StateManagement(emfXacml, thisPdpId);
925                 sm2.addObserver(pmStandbyStateChangeNotifier);
926                 
927                 logger.info("testHotStandby2: Running policy-management.Main class");
928                 PolicyManagementRunner policyManagementRunner = new PolicyManagementRunner(); //pdp1
929                 policyManagementRunner.start();
930                 
931                 logger.info("testHotStandby2: Runner started; Sleeping "
932                                 + interruptRecoveryTime + "ms before promoting/demoting");
933                 Thread.sleep(interruptRecoveryTime);
934
935                 logger.info("testHotStandby2: Runner started; promoting PDP=" + activePdpId);//pdpd2xs
936                 //at this point, the newly created pdp will have set the state to disabled/failed/cold standby
937                 //because it is stale. So, it cannot be promoted.  We need to call sm.enableNotFailed() so we
938                 //can promote it and demote the other pdp - else the other pdp will just spring back to providingservice
939                 sm.enableNotFailed();//pdp1
940                 sm.promote();
941                 String standbyStatus = sm.getStandbyStatus(activePdpId);
942                 logger.info("testHotStandby2: After promoting, PDP=" + activePdpId + " has standbyStatus="
943                                 + standbyStatus);
944                 
945                 // demoting PDP should ensure that state transits to hotstandby
946                 logger.info("testHotStandby2: Runner started; demoting PDP=" + thisPdpId);
947                 sm2.demote();//pdp1
948                 standbyStatus = sm.getStandbyStatus(thisPdpId);
949                 logger.info("testHotStandby2: After demoting, PDP=" + thisPdpId + " has standbyStatus="
950                                 + standbyStatus);
951                 
952                 logger.info("testHotStandby2: Sleeping "
953                                 + sleepTime
954                                 + "ms, to allow JpaDroolsPdpsConnector time to check droolspdpentity table");
955                 Thread.sleep(sleepTime);
956                 
957                 /*
958                  * Verify that this PDP, demoted to HOT_STANDBY, is now
959                  * re-designated and providing service.
960                  */
961                 droolsPdpEntity = conn.getPdp(thisPdpId);
962                 logger.info("testHotStandby2: After demoting PDP=" + activePdpId
963                                 + ", DESIGNATED=" + droolsPdpEntity.isDesignated()
964                                 + " for PDP=" + thisPdpId);
965                 assertTrue(droolsPdpEntity.isDesignated() == true);
966                 standbyStatus = sm2.getStandbyStatus(thisPdpId);
967                 logger.info("testHotStandby2: After demoting PDP=" + activePdpId
968                                 + ", PDP=" + thisPdpId + " has standbyStatus=" + standbyStatus);
969                 assertTrue(standbyStatus != null
970                                 && standbyStatus.equals(StateManagement.PROVIDING_SERVICE));
971                                 
972                 logger.info("testHotStandby2: Stopping policyManagementRunner");
973                 //policyManagementRunner.stopRunner();          
974
975                 logger.info("\n\ntestHotStandby2: Exiting\n\n");
976                 Thread.sleep(interruptRecoveryTime);
977
978         }
979         
980         /*
981          * 1) Inserts and designates this PDP, then verifies that startTransaction
982          * is successful.
983          * 
984          * 2) Demotes PDP, and verifies that because there is only one PDP, it will
985          * be immediately re-promoted, thus allowing startTransaction to be
986          * successful.
987          * 
988          * 3) Locks PDP and verifies that startTransaction results in
989          * AdministrativeStateException.
990          * 
991          * 4) Unlocks PDP and verifies that startTransaction results in
992          * StandbyStatusException.
993          * 
994          * 5) Promotes PDP and verifies that startTransaction is once again
995          * successful.
996          */
997         //@Ignore
998         //@Test
999         public void testLocking1() throws Exception {
1000                 logger.debug("testLocking1: Entry");
1001                 cleanXacmlDb();
1002                 cleanDroolsDb();                
1003                 
1004                 logger.debug("testLocking1: Reading IntegrityMonitorProperties");
1005                 Properties integrityMonitorProperties = new Properties();
1006                 integrityMonitorProperties.load(new FileInputStream(new File(
1007                                 "src/test/server/config/IntegrityMonitor.properties")));
1008                 IntegrityMonitorProperties.initProperties(integrityMonitorProperties);
1009                 String thisPdpId = IntegrityMonitorProperties
1010                                 .getProperty(IntegrityMonitorProperties.PDP_INSTANCE_ID);
1011
1012                 logger.debug("testLocking1: Reading xacmlPersistenceProperties");
1013                 Properties xacmlPersistenceProperties = new Properties();
1014                 xacmlPersistenceProperties.load(new FileInputStream(new File(
1015                                 "src/test/server/config/xacmlPersistence.properties")));
1016                 XacmlPersistenceProperties.initProperties(xacmlPersistenceProperties);
1017                 
1018                 logger.debug("testLocking1: Creating emfXacml");
1019                 EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory(
1020                                 "junitXacmlPU", xacmlPersistenceProperties);
1021                 
1022                 logger.debug("testLocking1: Reading droolsPersistenceProperties");
1023                 Properties droolsPersistenceProperties = new Properties();
1024                 droolsPersistenceProperties.load(new FileInputStream(new File(
1025                                 "src/test/server/config/droolsPersistence.properties")));
1026                 DroolsPersistenceProperties.initProperties(droolsPersistenceProperties);
1027
1028                 logger.debug("testLocking1: Creating emfDrools");
1029                 EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory(
1030                                 "junitDroolsPU", droolsPersistenceProperties);
1031                 
1032                 DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools);
1033                 
1034                 logger.debug("testLocking1: Cleaning up tables");
1035                 conn.deleteAllSessions();
1036                 conn.deleteAllPdps();
1037                 
1038                 /*
1039                  * Insert this PDP as designated.  Initial standby state will be 
1040                  * either null or cold standby.   
1041                  */
1042                 logger.debug("testLocking1: Inserting PDP=" + thisPdpId + " as designated");
1043                 DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, true, 4, new Date());
1044                 conn.insertPdp(pdp);
1045                 DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId);
1046                 logger.debug("testLocking1: After insertion, PDP=" + thisPdpId + " has DESIGNATED="
1047                                 + droolsPdpEntity.isDesignated());
1048                 assertTrue(droolsPdpEntity.isDesignated() == true);
1049                 
1050                 logger.debug("testLocking1: Instantiating stateManagement object");
1051                 StateManagement sm = new StateManagement(emfXacml, "dummy");
1052                 sm.deleteAllStateManagementEntities();
1053                 sm = new StateManagement(emfXacml, thisPdpId);
1054                 PMStandbyStateChangeNotifier pmStandbyStateChangeNotifier = new PMStandbyStateChangeNotifier();
1055                 sm.addObserver(pmStandbyStateChangeNotifier);
1056                                 
1057                 logger.debug("testLocking1: Running policy-management.Main class, designated="
1058                                 + conn.getPdp(thisPdpId).isDesignated());
1059                 PolicyManagementRunner policyManagementRunner = new PolicyManagementRunner();
1060                 policyManagementRunner.start();
1061                 
1062                 logger.debug("testLocking1: Runner started; Sleeping "
1063                                 + interruptRecoveryTime + "ms before promoting PDP="
1064                                 + thisPdpId);
1065                 Thread.sleep(interruptRecoveryTime);
1066
1067                 logger.debug("testLocking1: Promoting PDP=" + thisPdpId);
1068                 sm.promote();
1069
1070                 logger.debug("testLocking1: Sleeping "
1071                                 + sleepTime
1072                                 + "ms, to allow time for policy-management.Main class to come up, designated="
1073                                 + conn.getPdp(thisPdpId).isDesignated());
1074                 Thread.sleep(sleepTime);
1075                 
1076                 logger.debug("testLocking1: Waking up and invoking startTransaction on active PDP="
1077                                 + thisPdpId
1078                                 + ", designated="
1079                                 + conn.getPdp(thisPdpId).isDesignated());
1080                 DroolsPDPIntegrityMonitor droolsPdpIntegrityMonitor = (DroolsPDPIntegrityMonitor) IntegrityMonitor
1081                                 .getInstance();
1082                 try {
1083                         droolsPdpIntegrityMonitor.startTransaction();
1084                         droolsPdpIntegrityMonitor.endTransaction();
1085                         logger.debug("testLocking1: As expected, transaction successful");
1086                 } catch (AdministrativeStateException e) {
1087                         logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, message=" + e.getMessage());
1088                         assertTrue(false);
1089                 } catch (StandbyStatusException e) {
1090                         logger.error("testLocking1: Unexpectedly caught StandbyStatusException, message=" + e.getMessage());
1091                         assertTrue(false);
1092                 } catch (Exception e) {
1093                         logger.error("testLocking1: Unexpectedly caught Exception, message=" + e.getMessage());
1094                         assertTrue(false);
1095                 }
1096                 
1097                 // demoting should cause state to transit to hotstandby, followed by re-promotion,
1098                 // since there is only one PDP.
1099                 logger.debug("testLocking1: demoting PDP=" + thisPdpId);
1100                 sm = droolsPdpIntegrityMonitor.getStateManager();
1101                 sm.demote();
1102                 
1103                 logger.debug("testLocking1: sleeping" + electionWaitSleepTime
1104                                 + " to allow election handler to re-promote PDP=" + thisPdpId);
1105                 Thread.sleep(electionWaitSleepTime);
1106                                                                 
1107                 logger.debug("testLocking1: Invoking startTransaction on re-promoted PDP="
1108                                 + thisPdpId
1109                                 + ", designated="
1110                                 + conn.getPdp(thisPdpId).isDesignated());
1111                 try {
1112                         droolsPdpIntegrityMonitor.startTransaction();
1113                         droolsPdpIntegrityMonitor.endTransaction();
1114                         logger.debug("testLocking1: As expected, transaction successful");
1115                 } catch (AdministrativeStateException e) {
1116                         logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, message=" + e.getMessage());
1117                         assertTrue(false);
1118                 } catch (StandbyStatusException e) {
1119                         logger.error("testLocking1: Unexpectedly caught StandbyStatusException, message=" + e.getMessage());
1120                         assertTrue(false);
1121                 } catch (Exception e) {
1122                         logger.error("testLocking1: Unexpectedly caught Exception, message=" + e.getMessage());
1123                         assertTrue(false);
1124                 }
1125                 
1126                 // locking should cause state to transit to cold standby
1127                 logger.debug("testLocking1: locking PDP=" + thisPdpId);
1128                 sm.lock();
1129                 
1130                 // Just to avoid any race conditions, sleep a little after locking
1131                 logger.debug("testLocking1: Sleeping a few millis after locking, to avoid race condition");
1132                 Thread.sleep(100);
1133                 
1134                 logger.debug("testLocking1: Invoking startTransaction on locked PDP="
1135                                 + thisPdpId
1136                                 + ", designated="
1137                                 + conn.getPdp(thisPdpId).isDesignated());
1138                 try {
1139                         droolsPdpIntegrityMonitor.startTransaction();
1140                         logger.error("testLocking1: startTransaction unexpectedly successful");
1141                         assertTrue(false);
1142                 } catch (AdministrativeStateException e) {
1143                         logger.debug("testLocking1: As expected, caught AdministrativeStateException, message=" + e.getMessage());
1144                 } catch (StandbyStatusException e) {
1145                         logger.error("testLocking1: Unexpectedly caught StandbyStatusException, message=" + e.getMessage());
1146                         assertTrue(false);
1147                 } catch (Exception e) {
1148                         logger.error("testLocking1: Unexpectedly caught Exception, message=" + e.getMessage());
1149                         assertTrue(false);
1150                 } finally {
1151                         droolsPdpIntegrityMonitor.endTransaction();
1152                 }               
1153                 
1154                 // unlocking should cause state to transit to hot standby and then providing service
1155                 logger.debug("testLocking1: unlocking PDP=" + thisPdpId);
1156                 sm.unlock();
1157                 
1158                 // Just to avoid any race conditions, sleep a little after locking
1159                 logger.debug("testLocking1: Sleeping a few millis after unlocking, to avoid race condition");
1160                 Thread.sleep(electionWaitSleepTime);
1161                 
1162                 logger.debug("testLocking1: Invoking startTransaction on unlocked PDP="
1163                                 + thisPdpId
1164                                 + ", designated="
1165                                 + conn.getPdp(thisPdpId).isDesignated());
1166                 try {
1167                         droolsPdpIntegrityMonitor.startTransaction();
1168                         logger.error("testLocking1: startTransaction successful as expected");
1169                 } catch (AdministrativeStateException e) {
1170                         logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, message=" + e.getMessage());
1171                         assertTrue(false);
1172                 } catch (StandbyStatusException e) {
1173                         logger.debug("testLocking1: Unexpectedly caught StandbyStatusException, message=" + e.getMessage());
1174                         assertTrue(false);
1175                 } catch (Exception e) {
1176                         logger.error("testLocking1: Unexpectedly caught Exception, message=" + e.getMessage());
1177                         assertTrue(false);
1178                 } finally {
1179                         droolsPdpIntegrityMonitor.endTransaction();
1180                 }
1181                 
1182                 // demoting should cause state to transit to providing service
1183                 logger.debug("testLocking1: demoting PDP=" + thisPdpId);
1184                 sm.demote();
1185                 
1186                 // Just to avoid any race conditions, sleep a little after promoting
1187                 logger.debug("testLocking1: Sleeping a few millis after demoting, to avoid race condition");
1188                 Thread.sleep(100);
1189                 
1190                 logger.debug("testLocking1: Invoking startTransaction on demoted PDP="
1191                                 + thisPdpId
1192                                 + ", designated="
1193                                 + conn.getPdp(thisPdpId).isDesignated());
1194                 try {
1195                         droolsPdpIntegrityMonitor.startTransaction();
1196                         droolsPdpIntegrityMonitor.endTransaction();
1197                         logger.debug("testLocking1: Unexpectedly, transaction successful");
1198                         assertTrue(false);
1199                 } catch (AdministrativeStateException e) {
1200                         logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, message=" + e.getMessage());
1201                         assertTrue(false);
1202                 } catch (StandbyStatusException e) {
1203                         logger.error("testLocking1: As expected caught StandbyStatusException, message=" + e.getMessage());
1204                 } catch (Exception e) {
1205                         logger.error("testLocking1: Unexpectedly caught Exception, message=" + e.getMessage());
1206                         assertTrue(false);
1207                 }
1208                 
1209                 logger.debug("testLocking1: Stopping policyManagementRunner");
1210                 //policyManagementRunner.stopRunner();          
1211
1212                 logger.debug("\n\ntestLocking1: Exiting\n\n");
1213                 Thread.sleep(interruptRecoveryTime);
1214
1215         }
1216         
1217         /*
1218          * 1) Inserts and designates this PDP, then verifies that startTransaction
1219          * is successful.
1220          * 
1221          * 2) Inserts another PDP in hotstandby.
1222          * 
1223          * 3) Demotes this PDP, and verifies 1) that other PDP is not promoted (because one
1224          * PDP cannot promote another PDP) and 2) that this PDP is re-promoted.
1225          */
1226         //@Ignore
1227         //@Test
1228         public void testLocking2() throws Exception {
1229
1230                 logger.debug("\n\ntestLocking2: Entering\n\n");
1231                 cleanXacmlDb();
1232                 cleanDroolsDb();                
1233                 
1234                 logger.debug("testLocking2: Reading IntegrityMonitorProperties");
1235                 Properties integrityMonitorProperties = new Properties();
1236                 integrityMonitorProperties.load(new FileInputStream(new File(
1237                                 "src/test/server/config/IntegrityMonitor.properties")));
1238                 IntegrityMonitorProperties.initProperties(integrityMonitorProperties);
1239                 String thisPdpId = IntegrityMonitorProperties
1240                                 .getProperty(IntegrityMonitorProperties.PDP_INSTANCE_ID);
1241
1242                 logger.debug("testLocking2: Reading xacmlPersistenceProperties");
1243                 Properties xacmlPersistenceProperties = new Properties();
1244                 xacmlPersistenceProperties.load(new FileInputStream(new File(
1245                                 "src/test/server/config/xacmlPersistence.properties")));
1246                 XacmlPersistenceProperties.initProperties(xacmlPersistenceProperties);
1247                 
1248                 logger.debug("testLocking2: Creating emfXacml");
1249                 EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory(
1250                                 "junitXacmlPU", xacmlPersistenceProperties);
1251                 
1252                 logger.debug("testLocking2: Reading droolsPersistenceProperties");
1253                 Properties droolsPersistenceProperties = new Properties();
1254                 droolsPersistenceProperties.load(new FileInputStream(new File(
1255                                 "src/test/server/config/droolsPersistence.properties")));
1256                 DroolsPersistenceProperties.initProperties(droolsPersistenceProperties);
1257
1258                 logger.debug("testLocking2: Creating emfDrools");
1259                 EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory(
1260                                 "junitDroolsPU", droolsPersistenceProperties);
1261                 
1262                 DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools);
1263                 
1264                 logger.debug("testLocking2: Cleaning up tables");
1265                 conn.deleteAllSessions();
1266                 conn.deleteAllPdps();
1267                 
1268                 /*
1269                  * Insert this PDP as designated.  Initial standby state will be 
1270                  * either null or cold standby.   Demoting should transit state to
1271                  * hot standby.
1272                  */
1273                 logger.debug("testLocking2: Inserting PDP=" + thisPdpId + " as designated");
1274                 DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, true, 3, new Date());
1275                 conn.insertPdp(pdp);
1276                 DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId);
1277                 logger.debug("testLocking2: After insertion, PDP=" + thisPdpId + " has DESIGNATED="
1278                                 + droolsPdpEntity.isDesignated());
1279                 assertTrue(droolsPdpEntity.isDesignated() == true);
1280                 
1281                 logger.debug("testLocking2: Instantiating stateManagement object and promoting PDP=" + thisPdpId);
1282                 StateManagement sm = new StateManagement(emfXacml, "dummy");
1283                 sm.deleteAllStateManagementEntities();
1284                 sm = new StateManagement(emfXacml, thisPdpId);
1285                 PMStandbyStateChangeNotifier pmStandbyStateChangeNotifier = new PMStandbyStateChangeNotifier();
1286                 sm.addObserver(pmStandbyStateChangeNotifier);
1287                                 
1288                 /*
1289                  * Insert another PDP as not designated.  Initial standby state will be 
1290                  * either null or cold standby.   Demoting should transit state to
1291                  * hot standby.
1292                  */
1293                 String standbyPdpId = "pdp2";
1294                 logger.debug("testLocking2: Inserting PDP=" + standbyPdpId + " as not designated");
1295                 Date yesterday = DateUtils.addDays(new Date(), -1);
1296                 pdp = new DroolsPdpImpl(standbyPdpId, false, 4, yesterday);
1297                 conn.insertPdp(pdp);
1298                 droolsPdpEntity = conn.getPdp(standbyPdpId);
1299                 logger.debug("testLocking2: After insertion, PDP=" + standbyPdpId + " has DESIGNATED="
1300                                 + droolsPdpEntity.isDesignated());
1301                 assertTrue(droolsPdpEntity.isDesignated() == false);
1302                 
1303                 logger.debug("testLocking2: Demoting PDP=" + standbyPdpId);
1304                 StateManagement sm2 = new StateManagement(emfXacml, standbyPdpId);
1305                 sm2.addObserver(pmStandbyStateChangeNotifier);
1306                                 
1307                 logger.debug("testLocking2: Running policy-management.Main class");
1308                 PolicyManagementRunner policyManagementRunner = new PolicyManagementRunner();
1309                 policyManagementRunner.start();
1310                 
1311                 logger.debug("testLocking2: Runner started; Sleeping "
1312                                 + interruptRecoveryTime + "ms before promoting/demoting");
1313                 Thread.sleep(interruptRecoveryTime);
1314
1315                 logger.debug("testLocking2: Promoting PDP=" + thisPdpId);
1316                 sm.promote();
1317
1318                 // demoting PDP should ensure that state transits to hotstandby
1319                 logger.debug("testLocking2: Demoting PDP=" + standbyPdpId);
1320                 sm2.demote();
1321                 
1322                 logger.debug("testLocking2: Sleeping "
1323                                 + sleepTime
1324                                 + "ms, to allow time for policy-management.Main class to come up");
1325                 Thread.sleep(sleepTime);
1326                 
1327                 logger.debug("testLocking2: Waking up and invoking startTransaction on active PDP="
1328                                 + thisPdpId
1329                                 + ", designated="
1330                                 + conn.getPdp(thisPdpId).isDesignated());
1331                 DroolsPDPIntegrityMonitor droolsPdpIntegrityMonitor = (DroolsPDPIntegrityMonitor) IntegrityMonitor
1332                                 .getInstance();
1333                 try {
1334                         droolsPdpIntegrityMonitor.startTransaction();
1335                         droolsPdpIntegrityMonitor.endTransaction();
1336                         logger.debug("testLocking2: As expected, transaction successful");
1337                 } catch (AdministrativeStateException e) {
1338                         logger.error("testLocking2: Unexpectedly caught AdministrativeStateException, message=" + e.getMessage());
1339                         assertTrue(false);
1340                 } catch (StandbyStatusException e) {
1341                         logger.error("testLocking2: Unexpectedly caught StandbyStatusException, message=" + e.getMessage());
1342                         assertTrue(false);
1343                 } catch (Exception e) {
1344                         logger.error("testLocking2: Unexpectedly caught Exception, message=" + e.getMessage());
1345                         assertTrue(false);
1346                 }
1347                 
1348                 // demoting should cause state to transit to hotstandby followed by re-promotion.
1349                 logger.debug("testLocking2: demoting PDP=" + thisPdpId);
1350                 sm = droolsPdpIntegrityMonitor.getStateManager();
1351                 sm.demote();
1352                 
1353                 logger.debug("testLocking2: sleeping" + electionWaitSleepTime
1354                                 + " to allow election handler to re-promote PDP=" + thisPdpId);
1355                 Thread.sleep(electionWaitSleepTime);
1356                 
1357                 logger.debug("testLocking2: Waking up and invoking startTransaction on re-promoted PDP="
1358                                 + thisPdpId + ", designated="
1359                                 + conn.getPdp(thisPdpId).isDesignated());
1360                 try {
1361                         droolsPdpIntegrityMonitor.startTransaction();
1362                         droolsPdpIntegrityMonitor.endTransaction();
1363                         logger.debug("testLocking2: As expected, transaction successful");
1364                 } catch (AdministrativeStateException e) {
1365                         logger.error("testLocking2: Unexpectedly caught AdministrativeStateException, message=" + e.getMessage());
1366                         assertTrue(false);
1367                 } catch (StandbyStatusException e) {
1368                         logger.error("testLocking2: Unexpectedly caught StandbyStatusException, message=" + e.getMessage());
1369                         assertTrue(false);
1370                 } catch (Exception e) {
1371                         logger.error("testLocking2: Unexpectedly caught Exception, message=" + e.getMessage());
1372                         assertTrue(false);
1373                 }
1374                 
1375                 logger.debug("testLocking2: Verifying designated status for PDP="
1376                                 + standbyPdpId);
1377                 boolean standbyPdpDesignated = conn.getPdp(standbyPdpId).isDesignated();
1378                 assertTrue(standbyPdpDesignated == false);
1379                 
1380                 logger.debug("testLocking2: Stopping policyManagementRunner");
1381                 //policyManagementRunner.stopRunner();          
1382
1383                 logger.debug("\n\ntestLocking2: Exiting\n\n");
1384                 Thread.sleep(interruptRecoveryTime);
1385
1386         }
1387         
1388
1389         private class PolicyManagementRunner extends Thread {
1390
1391                 public void run() {
1392                         logger.info("PolicyManagementRunner.run: Entering");
1393                         String args[] = { "src/main/server/config" };
1394                         try {
1395                                 Main.main(args);
1396                         } catch (Exception e) {
1397                                 logger
1398                                                 .info("PolicyManagementRunner.run: Exception thrown from Main.main(), message="
1399                                                                 + e.getMessage());
1400                                 return;
1401                         }
1402                         logger.info("PolicyManagementRunner.run: Exiting");
1403                 }
1404                 
1405                 public void stopRunner() {
1406                         PolicyEngine.manager.shutdown();
1407                 }
1408
1409         }
1410         
1411 }