From dfe8fa8bc3e75c186589d21b619baa55454ef8a2 Mon Sep 17 00:00:00 2001 From: Jim Hahn Date: Wed, 14 Aug 2019 17:31:50 -0400 Subject: Use pseudo time for junits Modified feature-active-standby-management and feature-lifecycle to be able to use TestTimeMulti, eliminating the need for sleep() calls in the junit tests and speeding the tests up significantly. Also modified feature-active-standby-management to use a memory DB for its junit tests. Change-Id: I6d7ae61bb73cbb19ff405b8d9fb660e92732edbb Issue-ID: POLICY-1968 Signed-off-by: Jim Hahn --- feature-active-standby-management/pom.xml | 6 + .../drools/activestandby/ActiveStandbyFeature.java | 6 +- .../drools/activestandby/DroolsPdpEntity.java | 3 +- .../activestandby/DroolsPdpsElectionHandler.java | 23 +- .../onap/policy/drools/activestandby/Factory.java | 40 + .../activestandby/JpaDroolsPdpsConnector.java | 13 +- .../PmStandbyStateChangeNotifier.java | 37 +- .../drools/activestandby/AllSeemsWellTest.java | 378 +++++ .../policy/drools/activestandby/FactoryTest.java | 65 + .../PmStandbyStateChangeNotifierTest.java | 35 +- .../activestandby/StandbyStateManagementTest.java | 1529 ++++++++++++++++++ .../drools/controller/test/AllSeemsWellTest.java | 343 ----- .../test/StandbyStateManagementTest.java | 1615 -------------------- .../src/test/resources/META-INF/persistence.xml | 18 - .../feature-active-standby-management.properties | 2 +- .../asw/feature-state-management.properties | 4 +- .../feature-active-standby-management.properties | 2 +- .../resources/feature-state-management.properties | 2 +- 18 files changed, 2073 insertions(+), 2048 deletions(-) create mode 100644 feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/Factory.java create mode 100644 feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/AllSeemsWellTest.java create mode 100644 feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/FactoryTest.java create mode 100644 feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/StandbyStateManagementTest.java delete mode 100644 feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java delete mode 100644 feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/StandbyStateManagementTest.java (limited to 'feature-active-standby-management') diff --git a/feature-active-standby-management/pom.xml b/feature-active-standby-management/pom.xml index f8378f1a..2e776baf 100644 --- a/feature-active-standby-management/pom.xml +++ b/feature-active-standby-management/pom.xml @@ -157,6 +157,12 @@ ${project.version} test + + org.onap.policy.common + utils-test + ${policy.common.version} + test + com.h2database h2 diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java index d7c153db..91d30d74 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java @@ -21,14 +21,12 @@ package org.onap.policy.drools.activestandby; import java.io.IOException; -import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Properties; - import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; - +import org.onap.policy.common.im.MonitorTime; import org.onap.policy.drools.core.PolicySessionFeatureApi; import org.onap.policy.drools.features.PolicyEngineFeatureApi; import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; @@ -163,7 +161,7 @@ public class ActiveStandbyFeature implements ActiveStandbyFeatureApi, synchronized (myPdpSync) { if (myPdp == null) { - myPdp = new DroolsPdpImpl(resourceName,false,4,new Date()); + myPdp = new DroolsPdpImpl(resourceName,false,4,MonitorTime.getInstance().getDate()); } String siteName = ActiveStandbyProperties.getProperty(ActiveStandbyProperties.SITE_NAME); if (siteName == null) { diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java index 38ab6e4b..4175068f 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java @@ -32,6 +32,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import lombok.Getter; import lombok.Setter; +import org.onap.policy.common.im.MonitorTime; import org.onap.policy.drools.activestandby.DroolsPdpObject; @Entity @@ -72,7 +73,7 @@ public class DroolsPdpEntity extends DroolsPdpObject implements Serializable { * Constructor. */ public DroolsPdpEntity() { - updatedDate = new Date(); + updatedDate = MonitorTime.getInstance().getDate(); //When this is translated to a TimeStamp in MySQL, it assumes the date is relative //to the local timezone. So, a value of Date(0) is actually Dec 31 18:00:00 CST 1969 //which is an invalid value for the MySql TimeStamp diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java index 85cf88b3..5308cbe6 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java @@ -26,8 +26,9 @@ import java.util.Date; import java.util.List; import java.util.Timer; import java.util.TimerTask; - +import org.onap.policy.common.im.MonitorTime; import org.onap.policy.common.im.StateManagement; +import org.onap.policy.common.utils.time.CurrentTime; import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants; import org.slf4j.Logger; @@ -73,6 +74,8 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { private StateManagementFeatureApi stateManagementFeature; + private final CurrentTime currentTime = MonitorTime.getInstance(); + private static boolean isUnitTesting = false; private static boolean isStalled = false; @@ -112,14 +115,14 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { logger.error("Could not get pdpUpdateInterval property. Using default {} ", pdpUpdateInterval, e); } - Date now = new Date(); + Date now = currentTime.getDate(); // Retrieve the ms since the epoch final long nowMs = now.getTime(); // Create the timer which will update the updateDate in DroolsPdpEntity table. // This is the heartbeat - updateWorker = new Timer(); + updateWorker = Factory.getInstance().makeTimer(); // Schedule the TimerUpdateClass to run at 100 ms and run at pdpCheckInterval ms thereafter // NOTE: The first run of the TimerUpdateClass results in myPdp being added to the @@ -127,7 +130,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { updateWorker.scheduleAtFixedRate(new TimerUpdateClass(), 100, pdpCheckInterval); // Create the timer which will run the election algorithm - waitTimer = new Timer(); + waitTimer = Factory.getInstance().makeTimer(); // Schedule it to start in startMs ms // (so it will run after the updateWorker and run at pdpUpdateInterval ms thereafter @@ -264,7 +267,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { logger.debug("DesignatedWaiter.run: myPdp: {}; Returning, isDesignated= {}", isDesignated, myPdp.getPdpId()); - Date tmpDate = new Date(); + Date tmpDate = currentTime.getDate(); logger.debug("DesignatedWaiter.run (end of run) waitTimerLastRunDate = {}", tmpDate); waitTimerLastRunDate = tmpDate; @@ -559,7 +562,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { pdpsConnector.setDesignated(myPdp,false); isDesignated = false; - waitTimerLastRunDate = new Date(); + waitTimerLastRunDate = currentTime.getDate(); logger.debug("DesignatedWaiter.run (designatedPdp == null) waitTimerLastRunDate = {}", waitTimerLastRunDate); myPdp.setUpdatedDate(waitTimerLastRunDate); @@ -573,7 +576,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { try { //Keep the order like this. StateManagement is last since it triggers controller init myPdp.setDesignated(true); - myPdp.setDesignatedDate(new Date()); + myPdp.setDesignatedDate(currentTime.getDate()); pdpsConnector.setDesignated(myPdp, true); isDesignated = true; String standbyStatus = stateManagementFeature.getStandbyStatus(); @@ -613,7 +616,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { } } - waitTimerLastRunDate = new Date(); + waitTimerLastRunDate = currentTime.getDate(); logger.debug("DesignatedWaiter.run (designatedPdp.getPdpId().equals(myPdp.getPdpId())) " + "waitTimerLastRunDate = " + waitTimerLastRunDate); myPdp.setUpdatedDate(waitTimerLastRunDate); @@ -920,7 +923,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { synchronized (checkWaitTimerLock) { try { logger.debug("checkWaitTimer: entry"); - Date now = new Date(); + Date now = currentTime.getDate(); long nowMs = now.getTime(); long waitTimerMs = waitTimerLastRunDate.getTime(); @@ -951,7 +954,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { } private long getDWaiterStartMs() { - Date now = new Date(); + Date now = currentTime.getDate(); // Retrieve the ms since the epoch long nowMs = now.getTime(); diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/Factory.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/Factory.java new file mode 100644 index 00000000..fae70074 --- /dev/null +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/Factory.java @@ -0,0 +1,40 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 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.onap.policy.drools.activestandby; + +import java.util.Timer; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; + +/** + * Factory for creating various objects. + */ +public class Factory { + + @Getter + @Setter(AccessLevel.PROTECTED) + private static Factory instance = new Factory(); + + public Timer makeTimer() { + return new Timer(); + } +} diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java index ed53f55c..1830d055 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java @@ -30,7 +30,8 @@ import javax.persistence.EntityManagerFactory; import javax.persistence.FlushModeType; import javax.persistence.LockModeType; import javax.persistence.Query; - +import org.onap.policy.common.im.MonitorTime; +import org.onap.policy.common.utils.time.CurrentTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,6 +44,8 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { private static final Logger logger = LoggerFactory.getLogger(JpaDroolsPdpsConnector.class); private EntityManagerFactory emf; + private final CurrentTime currentTime = MonitorTime.getInstance(); + //not sure if we want to use the same entity manager factory //for drools session and pass it in here, or create a new one @@ -114,7 +117,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { if (droolsPdpsList.size() == 1 && (droolsPdpsList.get(0) instanceof DroolsPdpEntity)) { droolsPdpEntity = (DroolsPdpEntity)droolsPdpsList.get(0); em.refresh(droolsPdpEntity); //Make sure we have current values - Date currentDate = new Date(); + Date currentDate = currentTime.getDate(); long difference = currentDate.getTime() - droolsPdpEntity.getUpdatedDate().getTime(); //just set some kind of default here long pdpTimeout = 15000; @@ -156,7 +159,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { droolsPdpEntity.setDesignated(pdp.isDesignated()); //The isDesignated value is not the same and the new one == true if (pdp.isDesignated()) { - droolsPdpEntity.setDesignatedDate(new Date()); + droolsPdpEntity.setDesignatedDate(currentTime.getDate()); } } em.getTransaction().commit(); @@ -255,7 +258,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { if (designated) { em.refresh(droolsPdpEntity); //make sure we get the DB value if (!droolsPdpEntity.isDesignated()) { - droolsPdpEntity.setDesignatedDate(new Date()); + droolsPdpEntity.setDesignatedDate(currentTime.getDate()); } } @@ -369,7 +372,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { // time box that may be. // If the the PDP is not current, we should mark it as not primary in // the database - Date currentDate = new Date(); + Date currentDate = currentTime.getDate(); long difference = currentDate.getTime() - pdp.getUpdatedDate().getTime(); // just set some kind of default here diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java index 7669cc22..735e3a2a 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java @@ -20,31 +20,12 @@ package org.onap.policy.drools.activestandby; -/* - * Per MultiSite_v1-10.ppt: - * - * Extends the StateChangeNotifier class and overwrites the abstract handleStateChange() method to get state changes - * and do the following: - * - * When the Standby Status changes (from providingservice) to hotstandby or coldstandby, - * the Active/Standby selection algorithm must stand down if the PDP-D is currently the lead/active node - * and allow another PDP-D to take over. It must also call lock on all engines in the engine management. - * - * When the Standby Status changes from (hotstandby) to coldstandby, the Active/Standby algorithm must NOT assume - * the active/lead role. - * - * When the Standby Status changes (from coldstandby or providingservice) to hotstandby, - * the Active/Standby algorithm may assume the active/lead role if the active/lead fails. - * - * When the Standby Status changes to providingservice (from hotstandby or coldstandby) call unlock on all - * engines in the engine management layer. - */ -import java.util.Date; import java.util.Timer; import java.util.TimerTask; - +import org.onap.policy.common.im.MonitorTime; import org.onap.policy.common.im.StateChangeNotifier; import org.onap.policy.common.im.StateManagement; +import org.onap.policy.common.utils.time.CurrentTime; import org.onap.policy.drools.system.PolicyEngine; import org.onap.policy.drools.system.PolicyEngineConstants; import org.slf4j.Logger; @@ -89,6 +70,8 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { private long waitInterval; private boolean isNowActivating; private String previousStandbyStatus; + private final CurrentTime currentTime = MonitorTime.getInstance(); + private final Factory timerFactory = Factory.getInstance(); public static final String NONE = "none"; public static final String UNSUPPORTED = "unsupported"; public static final String HOTSTANDBY_OR_COLDSTANDBY = "hotstandby_or_coldstandby"; @@ -101,7 +84,7 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { pdpUpdateInterval = Integer.parseInt(ActiveStandbyProperties.getProperty(ActiveStandbyProperties.PDP_UPDATE_INTERVAL)); isWaitingForActivation = false; - startTimeWaitingForActivationMs = new Date().getTime(); + startTimeWaitingForActivationMs = currentTime.getMillis(); // delay the activate so the DesignatedWaiter can run twice - give it an extra 2 seconds waitInterval = 2 * pdpUpdateInterval + 2000L; isNowActivating = false; @@ -222,11 +205,11 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { // Just in case there is an old timer hanging around logger.debug("handleStateChange: PROVIDING_SERVICE cancelling delayActivationTimer."); cancelTimer(); - delayActivateTimer = makeTimer(); + delayActivateTimer = timerFactory.makeTimer(); // delay the activate so the DesignatedWaiter can run twice delayActivateTimer.schedule(new DelayActivateClass(), waitInterval); isWaitingForActivation = true; - startTimeWaitingForActivationMs = new Date().getTime(); + startTimeWaitingForActivationMs = currentTime.getMillis(); logger.debug("handleStateChange: PROVIDING_SERVICE scheduling delayActivationTimer in {} ms", waitInterval); } else { @@ -244,7 +227,7 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { if (isWaitingForActivation) { logger.debug("handleStateChange: PROVIDING_SERVICE isWaitingForActivation = {}", isWaitingForActivation); - long now = new Date().getTime(); + long now = currentTime.getMillis(); long waitTimeMs = now - startTimeWaitingForActivationMs; if (waitTimeMs > 3 * waitInterval) { logger.debug("handleStateChange: PROVIDING_SERVICE looks like the activation wait timer " @@ -327,8 +310,4 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { protected PolicyEngine getPolicyEngineManager() { return PolicyEngineConstants.getManager(); } - - protected Timer makeTimer() { - return new Timer(); - } } diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/AllSeemsWellTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/AllSeemsWellTest.java new file mode 100644 index 00000000..cb7e4c3f --- /dev/null +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/AllSeemsWellTest.java @@ -0,0 +1,378 @@ +/* + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017-2019 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.onap.policy.drools.activestandby; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Date; +import java.util.Properties; +import java.util.concurrent.Callable; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import org.apache.commons.lang3.time.DateUtils; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.common.im.IntegrityMonitor; +import org.onap.policy.common.im.IntegrityMonitorException; +import org.onap.policy.common.im.MonitorTime; +import org.onap.policy.common.im.StateManagement; +import org.onap.policy.common.utils.time.CurrentTime; +import org.onap.policy.common.utils.time.PseudoTimer; +import org.onap.policy.common.utils.time.TestTimeMulti; +import org.onap.policy.drools.core.PolicySessionFeatureApi; +import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; +import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants; +import org.powermock.reflect.Whitebox; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/* + * Testing the allSeemsWell interface to verify that it correctly affects the + * operational state. + */ + +public class AllSeemsWellTest { + private static final Logger logger = LoggerFactory.getLogger(AllSeemsWellTest.class); + + private static final String MONITOR_FIELD_NAME = "instance"; + private static final String HANDLER_INSTANCE_FIELD = "electionHandler"; + + /* + * Currently, the DroolsPdpsElectionHandler.DesignationWaiter is invoked every 1 seconds, starting + * at the start of the next multiple of pdpUpdateInterval, but with a minimum of 5 sec cushion + * to ensure that we wait for the DesignationWaiter to do its job, before + * checking the results. Add a few seconds for safety + */ + + private static final int SLEEP_TIME_SEC = 10; + + /* + * DroolsPdpsElectionHandler runs every 1 seconds, so it takes 10 seconds for the + * checkWaitTimer() method to time out and call allSeemsWell which then requires + * the forward progress counter to go stale which should add an additional 5 sec. + */ + + private static final int STALLED_ELECTION_HANDLER_SLEEP_TIME_SEC = 15; + + /* + * As soon as the election hander successfully runs, it will resume the forward progress. + * If the election handler runs ever 1 sec and test transaction is run every 1 sec and + * then fpc is written every 1 sec and then the fpc is checked every 2 sec, that could + * take a total of 5 sec to recognize the resumption of progress. So, add 1 for safety. + */ + private static final int RESUMED_ELECTION_HANDLER_SLEEP_TIME_SEC = 6; + + private static EntityManagerFactory emfx; + private static EntityManagerFactory emfd; + private static EntityManager emx; + private static EntityManager emd; + private static EntityTransaction et; + + private static final String CONFIG_DIR = "src/test/resources/asw"; + + private static CurrentTime saveTime; + private static Factory saveFactory; + + private TestTimeMulti testTime; + + /* + * See the IntegrityMonitor.getJmxUrl() method for the rationale behind this jmx related processing. + */ + + /** + * Setup the class. + * + * @throws Exception exception + */ + @BeforeClass + public static void setUpClass() throws Exception { + + String userDir = System.getProperty("user.dir"); + logger.debug("setUpClass: userDir={}", userDir); + System.setProperty("com.sun.management.jmxremote.port", "9980"); + System.setProperty("com.sun.management.jmxremote.authenticate","false"); + + DroolsPdpsElectionHandler.setIsUnitTesting(true); + + saveTime = Whitebox.getInternalState(MonitorTime.class, MONITOR_FIELD_NAME); + saveFactory = Factory.getInstance(); + + resetInstanceObjects(); + + //Create the data access for xacml db + Properties stateManagementProperties = loadStateManagementProperties(); + + emfx = Persistence.createEntityManagerFactory("junitXacmlPU", stateManagementProperties); + + // Create an entity manager to use the DB + emx = emfx.createEntityManager(); + + //Create the data access for drools db + Properties activeStandbyProperties = loadActiveStandbyProperties(); + + emfd = Persistence.createEntityManagerFactory("junitDroolsPU", activeStandbyProperties); + + // Create an entity manager to use the DB + emd = emfd.createEntityManager(); + } + + /** + * Restores the system state. + * + * @throws IntegrityMonitorException if the integrity monitor cannot be shut down + */ + @AfterClass + public static void tearDownClass() throws IntegrityMonitorException { + resetInstanceObjects(); + + Whitebox.setInternalState(MonitorTime.class, MONITOR_FIELD_NAME, saveTime); + Factory.setInstance(saveFactory); + + DroolsPdpsElectionHandler.setIsUnitTesting(false); + + emd.close(); + emfd.close(); + + emx.close(); + emfx.close(); + } + + /** + * Setup. + * + * @throws Exception exception + */ + @Before + public void setUp() throws Exception { + resetInstanceObjects(); + + // set test time + testTime = new TestTimeMulti(); + Whitebox.setInternalState(MonitorTime.class, MONITOR_FIELD_NAME, testTime); + + Factory factory = mock(Factory.class); + when(factory.makeTimer()).thenAnswer(ans -> new PseudoTimer(testTime)); + Factory.setInstance(factory); + } + + private static void resetInstanceObjects() throws IntegrityMonitorException { + IntegrityMonitor.setUnitTesting(true); + IntegrityMonitor.deleteInstance(); + IntegrityMonitor.setUnitTesting(false); + + Whitebox.setInternalState(ActiveStandbyFeature.class, HANDLER_INSTANCE_FIELD, (Object) null); + + } + + /** + * Clean the xacml database. + */ + public void cleanXacmlDb() { + et = emx.getTransaction(); + + et.begin(); + // Make sure we leave the DB clean + emx.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); + emx.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); + emx.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); + emx.flush(); + et.commit(); + } + + /** + * Clean the drools database. + */ + public void cleanDroolsDb() { + et = emd.getTransaction(); + + et.begin(); + // Make sure we leave the DB clean + emd.createQuery("DELETE FROM DroolsPdpEntity").executeUpdate(); + emd.flush(); + et.commit(); + } + + + // Tests hot standby when there is only one PDP. + + //@Ignore + @Test + public void testAllSeemsWell() throws Exception { + + logger.debug("\n\ntestAllSeemsWell: Entering\n\n"); + cleanXacmlDb(); + cleanDroolsDb(); + + Properties stateManagementProperties = loadStateManagementProperties(); + + logger.debug("testAllSeemsWell: Creating emfXacml"); + final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( + "junitXacmlPU", stateManagementProperties); + + Properties activeStandbyProperties = loadActiveStandbyProperties(); + final String thisPdpId = activeStandbyProperties + .getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.debug("testAllSeemsWell: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); + + logger.debug("testAllSeemsWell: Cleaning up tables"); + conn.deleteAllPdps(); + + /* + * Insert this PDP as not designated. Initial standby state will be + * either null or cold standby. Demoting should transit state to + * hot standby. + */ + + logger.debug("testAllSeemsWell: Inserting PDP={} as not designated", thisPdpId); + Date yesterday = DateUtils.addDays(testTime.getDate(), -1); + DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday); + conn.insertPdp(pdp); + DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testAllSeemsWell: After insertion, PDP={} has DESIGNATED={}", + thisPdpId, droolsPdpEntity.isDesignated()); + assertTrue(droolsPdpEntity.isDesignated() == false); + + logger.debug("testAllSeemsWell: Instantiating stateManagement object"); + StateManagement sm = new StateManagement(emfXacml, "dummy"); + sm.deleteAllStateManagementEntities(); + + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureApi stateManagementFeatureApi = null; + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + stateManagementFeatureApi = feature; + logger.debug("testAllSeemsWell stateManagementFeature.getResourceName(): {}", + stateManagementFeatureApi.getResourceName()); + break; + } + assertNotNull(stateManagementFeatureApi); + + final StateManagementFeatureApi smf = stateManagementFeatureApi; + + // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature + // that has been created. + ActiveStandbyFeatureApi activeStandbyFeature = null; + for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + activeStandbyFeature = feature; + logger.debug("testAllSeemsWell activeStandbyFeature.getResourceName(): {}", + activeStandbyFeature.getResourceName()); + break; + } + assertNotNull(activeStandbyFeature); + + + logger.debug("testAllSeemsWell: Demoting PDP={}", thisPdpId); + // demoting should cause state to transit to hotstandby + smf.demote(); + + + logger.debug("testAllSeemsWell: Sleeping {} s, to allow JpaDroolsPdpsConnector " + + "time to check droolspdpentity table", SLEEP_TIME_SEC); + waitForCondition(() -> conn.getPdp(thisPdpId).isDesignated(), SLEEP_TIME_SEC); + + // Verify that this formerly un-designated PDP in HOT_STANDBY is now designated and providing service. + + droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testAllSeemsWell: After sm.demote() invoked, DESIGNATED= {} " + + "for PDP= {}", droolsPdpEntity.isDesignated(), thisPdpId); + assertTrue(droolsPdpEntity.isDesignated() == true); + String standbyStatus = smf.getStandbyStatus(thisPdpId); + logger.debug("testAllSeemsWell: After demotion, PDP= {} " + + "has standbyStatus= {}", thisPdpId, standbyStatus); + assertTrue(standbyStatus != null && standbyStatus.equals(StateManagement.PROVIDING_SERVICE)); + + //Now we want to stall the election handler and see the if AllSeemsWell will make the + //standbystatus = coldstandby + + DroolsPdpsElectionHandler.setIsStalled(true); + + logger.debug("testAllSeemsWell: Sleeping {} s, to allow checkWaitTimer to recognize " + + "the election handler has stalled and for the testTransaction to fail to " + + "increment forward progress and for the lack of forward progress to be recognized.", + STALLED_ELECTION_HANDLER_SLEEP_TIME_SEC); + + + //It takes 10x the update interval (1 sec) before the watcher will declare the election handler dead + //and that just stops forward progress counter. So, the fp monitor must then run to determine + // if the fpc has stalled. That will take about another 5 sec. + waitForCondition(() -> smf.getStandbyStatus().equals(StateManagement.COLD_STANDBY), + STALLED_ELECTION_HANDLER_SLEEP_TIME_SEC); + + logger.debug("testAllSeemsWell: After isStalled=true, PDP= {} " + + "has standbyStatus= {}", thisPdpId, smf.getStandbyStatus(thisPdpId)); + + assertTrue(smf.getStandbyStatus().equals(StateManagement.COLD_STANDBY)); + + //Now lets resume the election handler + DroolsPdpsElectionHandler.setIsStalled(false); + + waitForCondition(() -> smf.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE), + RESUMED_ELECTION_HANDLER_SLEEP_TIME_SEC); + + logger.debug("testAllSeemsWell: After isStalled=false, PDP= {} " + + "has standbyStatus= {}", thisPdpId, smf.getStandbyStatus(thisPdpId)); + + assertTrue(smf.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); + + //resumedElectionHandlerSleepTime = 5000; + logger.debug("\n\ntestAllSeemsWell: Exiting\n\n"); + + } + + private static Properties loadStateManagementProperties() throws IOException { + try (FileInputStream input = new FileInputStream(CONFIG_DIR + "/feature-state-management.properties")) { + Properties props = new Properties(); + props.load(input); + return props; + } + } + + private static Properties loadActiveStandbyProperties() throws IOException { + try (FileInputStream input = + new FileInputStream(CONFIG_DIR + "/feature-active-standby-management.properties")) { + Properties props = new Properties(); + props.load(input); + return props; + } + } + + private void waitForCondition(Callable testCondition, int timeoutInSeconds) throws InterruptedException { + testTime.waitUntil(testCondition); + } +} diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/FactoryTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/FactoryTest.java new file mode 100644 index 00000000..8a166954 --- /dev/null +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/FactoryTest.java @@ -0,0 +1,65 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 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.onap.policy.drools.activestandby; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class FactoryTest { + private static Factory saveFactory; + + private Factory factory; + + @BeforeClass + public static void setUpBeforeClass() { + saveFactory = Factory.getInstance(); + assertNotNull(saveFactory); + } + + @AfterClass + public static void tearDownAfterClass() { + Factory.setInstance(saveFactory); + } + + @Before + public void setUp() { + factory = new Factory(); + } + + @Test + public void testMakeTimer() { + assertNotNull(factory.makeTimer()); + } + + @Test + public void testGetInstance_testSetInstance() { + Factory.setInstance(factory); + assertSame(factory, Factory.getInstance()); + + // repeat - should be the same + assertSame(factory, Factory.getInstance()); + } +} diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifierTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifierTest.java index 28d3b439..4a89d257 100644 --- a/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifierTest.java +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifierTest.java @@ -32,6 +32,7 @@ import static org.mockito.Mockito.when; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; +import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -47,6 +48,11 @@ public class PmStandbyStateChangeNotifierTest { private static final long UPDATE_INTERVAL = 100; private static final long WAIT_INTERVAL = 2 * UPDATE_INTERVAL + 2000; + private static Factory saveFactory; + + @Mock + private Factory factory; + @Mock private PolicyEngine engmgr; @@ -68,16 +74,25 @@ public class PmStandbyStateChangeNotifierTest { props.setProperty(ActiveStandbyProperties.PDP_UPDATE_INTERVAL, String.valueOf(UPDATE_INTERVAL)); ActiveStandbyProperties.initProperties(props); + + saveFactory = Factory.getInstance(); + } + + @AfterClass + public static void tearDownAfterClass() { + Factory.setInstance(saveFactory); } /** * Initializes objects, including the notifier. */ - @Before public void setUp() { MockitoAnnotations.initMocks(this); + Factory.setInstance(factory); + when(factory.makeTimer()).thenReturn(timer); + notifier = new MyNotifier(); } @@ -167,12 +182,7 @@ public class PmStandbyStateChangeNotifierTest { @Test public void testHandleStateChange_ProvidingService_Ex() { - notifier = new MyNotifier() { - @Override - protected Timer makeTimer() { - throw new MyException(); - } - }; + when(factory.makeTimer()).thenThrow(new MyException()); when(mgmt.getStandbyStatus()).thenReturn(StateManagement.PROVIDING_SERVICE); notifier.update(mgmt, null); @@ -256,22 +266,11 @@ public class PmStandbyStateChangeNotifierTest { new PmStandbyStateChangeNotifier().getPolicyEngineManager(); } - @Test - public void testMakeTimer() { - // use real object with real method - new PmStandbyStateChangeNotifier().makeTimer().cancel(); - } - private class MyNotifier extends PmStandbyStateChangeNotifier { @Override protected PolicyEngine getPolicyEngineManager() { return engmgr; } - - @Override - protected Timer makeTimer() { - return timer; - } } private static class MyException extends RuntimeException { diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/StandbyStateManagementTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/StandbyStateManagementTest.java new file mode 100644 index 00000000..143aaf31 --- /dev/null +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/StandbyStateManagementTest.java @@ -0,0 +1,1529 @@ +/*- + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017-2019 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.onap.policy.drools.activestandby; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Properties; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import org.apache.commons.lang3.time.DateUtils; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.common.im.AdministrativeStateException; +import org.onap.policy.common.im.IntegrityMonitor; +import org.onap.policy.common.im.IntegrityMonitorException; +import org.onap.policy.common.im.MonitorTime; +import org.onap.policy.common.im.StandbyStatusException; +import org.onap.policy.common.im.StateManagement; +import org.onap.policy.common.utils.time.CurrentTime; +import org.onap.policy.common.utils.time.PseudoTimer; +import org.onap.policy.common.utils.time.TestTimeMulti; +import org.onap.policy.drools.core.PolicySessionFeatureApi; +import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; +import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants; +import org.powermock.reflect.Whitebox; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/* + * All JUnits are designed to run in the local development environment + * where they have write privileges and can execute time-sensitive + * tasks. + * + * These tests can be run as JUnits, but there is some issue with running them + * as part of a "mvn install" build. Also, they take a very long time to run + * due to many real time breaks. Consequently, they are marked as @Ignore and + * only run from the desktop. + */ + +public class StandbyStateManagementTest { + private static final Logger logger = LoggerFactory.getLogger(StandbyStateManagementTest.class); + + private static final String MONITOR_FIELD_NAME = "instance"; + private static final String HANDLER_INSTANCE_FIELD = "electionHandler"; + + /* + * Currently, the DroolsPdpsElectionHandler.DesignationWaiter is invoked every 1 seconds, starting + * at the start of the next multiple of pdpUpdateInterval, but with a minimum of 5 sec cushion + * to ensure that we wait for the DesignationWaiter to do its job, before + * checking the results. Add a few seconds for safety + */ + + private static final long SLEEP_TIME = 10000; + + /* + * DroolsPdpsElectionHandler runs every 1 seconds, so a 6 second sleep should be + * plenty to ensure it has time to re-promote this PDP. + */ + + private static final long ELECTION_WAIT_SLEEP_TIME = 6000; + + /* + * Sleep a few seconds after each test to allow interrupt (shutdown) recovery. + */ + + private static final long INTERRUPT_RECOVERY_TIME = 5000; + + private static EntityManagerFactory emfx; + private static EntityManagerFactory emfd; + private static EntityManager emx; + private static EntityManager emd; + private static EntityTransaction et; + + private static final String CONFIG_DIR = "src/test/resources"; + + private static CurrentTime saveTime; + private static Factory saveFactory; + + private TestTimeMulti testTime; + + /* + * See the IntegrityMonitor.getJmxUrl() method for the rationale behind this jmx related processing. + */ + + /** + * Setup the class. + * + * @throws Exception exception + */ + @BeforeClass + public static void setUpClass() throws Exception { + + String userDir = System.getProperty("user.dir"); + logger.debug("setUpClass: userDir={}", userDir); + System.setProperty("com.sun.management.jmxremote.port", "9980"); + System.setProperty("com.sun.management.jmxremote.authenticate","false"); + + saveTime = Whitebox.getInternalState(MonitorTime.class, MONITOR_FIELD_NAME); + saveFactory = Factory.getInstance(); + + resetInstanceObjects(); + + //Create the data access for xacml db + Properties stateManagementProperties = loadStateManagementProperties(); + + emfx = Persistence.createEntityManagerFactory("junitXacmlPU", stateManagementProperties); + + // Create an entity manager to use the DB + emx = emfx.createEntityManager(); + + //Create the data access for drools db + Properties activeStandbyProperties = loadActiveStandbyProperties(); + + emfd = Persistence.createEntityManagerFactory("junitDroolsPU", activeStandbyProperties); + + // Create an entity manager to use the DB + emd = emfd.createEntityManager(); + } + + /** + * Restores the system state. + * + * @throws IntegrityMonitorException if the integrity monitor cannot be shut down + */ + @AfterClass + public static void tearDownClass() throws IntegrityMonitorException { + resetInstanceObjects(); + + Whitebox.setInternalState(MonitorTime.class, MONITOR_FIELD_NAME, saveTime); + Factory.setInstance(saveFactory); + + emd.close(); + emfd.close(); + + emx.close(); + emfx.close(); + } + + /** + * Setup. + * + * @throws Exception exception + */ + @Before + public void setUp() throws Exception { + resetInstanceObjects(); + + // set test time + testTime = new TestTimeMulti(); + Whitebox.setInternalState(MonitorTime.class, MONITOR_FIELD_NAME, testTime); + + Factory factory = mock(Factory.class); + when(factory.makeTimer()).thenAnswer(ans -> new PseudoTimer(testTime)); + Factory.setInstance(factory); + } + + private static void resetInstanceObjects() throws IntegrityMonitorException { + IntegrityMonitor.setUnitTesting(true); + IntegrityMonitor.deleteInstance(); + IntegrityMonitor.setUnitTesting(false); + + Whitebox.setInternalState(ActiveStandbyFeature.class, HANDLER_INSTANCE_FIELD, (Object) null); + + } + + /** + * Clean up the xacml database. + * + */ + public void cleanXacmlDb() { + et = emx.getTransaction(); + + et.begin(); + // Make sure we leave the DB clean + emx.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); + emx.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); + emx.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); + emx.flush(); + et.commit(); + } + + /** + * Clean up the drools db. + */ + public void cleanDroolsDb() { + et = emd.getTransaction(); + + et.begin(); + // Make sure we leave the DB clean + emd.createQuery("DELETE FROM DroolsPdpEntity").executeUpdate(); + emd.flush(); + et.commit(); + } + + /* + * These JUnit tests must be run one at a time in an eclipse environment + * by right-clicking StandbyStateManagementTest and selecting + * "Run As" -> "JUnit Test". + * + * They will run successfully when you run all of them under runAllTests(), + * however, you will get all sorts of non-fatal errors in the log and on the + * console that result from overlapping threads that are not terminated at the + * end of each test. The problem is that the JUnit environment does not terminate + * all the test threads between tests. This is true even if you break each JUnit + * into a separate file. Consequently, all the tests would have to be refactored + * so all test object initializations are coordinated. In other words, you + * retrieve the ActiveStandbyFeature instance and other class instances only once + * at the beginning of the JUnits and then reuse them throughout the tests. + * Initialization of the state of the objects is pretty straight forward as it + * just amounts to manipulating the entries in StateManagementEntity and + * DroolsPdpEntity tables. However, some thought needs to be given to how to + * "pause" the processing in ActiveStandbyFeature class. I think we could "pause" + * it by calling globalInit() which will, I think, restart it. So long as it + * does not create a new instance, it will force it to go through an initialization + * cycle which includes a "pause" at the beginning of proecessing. We just must + * be sure it does not create another instance - which may mean we need to add + * a factory interface instead of calling the constructor directly. + */ + + + //@Ignore + @Test + public void runAllTests() throws Exception { + testColdStandby(); + testHotStandby1(); + testHotStandby2(); + testLocking1(); + testLocking2(); + testPmStandbyStateChangeNotifier(); + testSanitizeDesignatedList(); + testComputeMostRecentPrimary(); + testComputeDesignatedPdp(); + } + + /** + * Test the standby state change notifier. + * + * @throws Exception exception + */ + //@Ignore + //@Test + public void testPmStandbyStateChangeNotifier() throws Exception { + logger.debug("\n\ntestPmStandbyStateChangeNotifier: Entering\n\n"); + cleanXacmlDb(); + + logger.debug("testPmStandbyStateChangeNotifier: Reading activeStandbyProperties"); + + Properties activeStandbyProperties = loadActiveStandbyProperties(); + + String resourceName = "testPMS"; + activeStandbyProperties.setProperty("resource.name", resourceName); + ActiveStandbyProperties.initProperties(activeStandbyProperties); + + logger.debug("testPmStandbyStateChangeNotifier: Getting StateManagement instance"); + + StateManagement sm = new StateManagement(emfx, resourceName); + + //Create an instance of the Observer + PmStandbyStateChangeNotifier pmNotifier = new PmStandbyStateChangeNotifier(); + + //Register the PmStandbyStateChangeNotifier Observer + sm.addObserver(pmNotifier); + + //At this point the standbystatus = 'null' + sm.lock(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.NULL_VALUE)); + + sm.unlock(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.NULL_VALUE)); + + //Adding standbystatus=hotstandby + sm.demote(); + System.out.println(pmNotifier.getPreviousStandbyStatus()); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals( + PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + + //Now making standbystatus=coldstandby + sm.lock(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals( + PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + + //standbystatus = hotstandby + sm.unlock(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals( + PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + + //standbystatus = providingservice + sm.promote(); + //The previousStandbyStatus is not updated until after the delay activation expires + assertTrue(pmNotifier.getPreviousStandbyStatus().equals( + PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + + //Sleep long enough for the delayActivationTimer to run + sleep(5000); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); + + //standbystatus = providingservice + sm.promote(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); + + //standbystatus = coldstandby + sm.lock(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals( + PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + + //standbystatus = hotstandby + sm.unlock(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals( + PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + + //standbystatus = hotstandby + sm.demote(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals( + PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + } + + /** + * Test sanitize designated list. + * + * @throws Exception exception + */ + //@Ignore + //@Test + public void testSanitizeDesignatedList() throws Exception { + + logger.debug("\n\ntestSanitizeDesignatedList: Entering\n\n"); + + // Get a DroolsPdpsConnector + + Properties activeStandbyProperties = loadActiveStandbyProperties(); + + logger.debug("testSanitizeDesignatedList: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + final DroolsPdpsConnector droolsPdpsConnector = new JpaDroolsPdpsConnector(emfDrools); + + // Create 4 pdpd all not designated + + DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, testTime.getDate()); + DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, testTime.getDate()); + DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, testTime.getDate()); + DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, testTime.getDate()); + + List listOfDesignated = new ArrayList(); + listOfDesignated.add(pdp1); + listOfDesignated.add(pdp2); + listOfDesignated.add(pdp3); + listOfDesignated.add(pdp4); + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureApi stateManagementFeature = null; + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + stateManagementFeature = feature; + logger.debug("testColdStandby stateManagementFeature.getResourceName(): {}", + stateManagementFeature.getResourceName()); + break; + } + assertNotNull(stateManagementFeature); + + + DroolsPdpsElectionHandler droolsPdpsElectionHandler = new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1); + + listOfDesignated = droolsPdpsElectionHandler.santizeDesignatedList(listOfDesignated); + + logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size = {}\n\n",listOfDesignated.size()); + + assertTrue(listOfDesignated.size() == 4); + + // Now make 2 designated + + pdp1.setDesignated(true); + pdp2.setDesignated(true); + + listOfDesignated = droolsPdpsElectionHandler.santizeDesignatedList(listOfDesignated); + + logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size after 2 designated = {}\n\n", + listOfDesignated.size()); + + assertTrue(listOfDesignated.size() == 2); + assertTrue(listOfDesignated.contains(pdp1)); + assertTrue(listOfDesignated.contains(pdp2)); + + + // Now all are designated. But, we have to add back the previously non-designated nodes + + pdp3.setDesignated(true); + pdp4.setDesignated(true); + listOfDesignated.add(pdp3); + listOfDesignated.add(pdp4); + + listOfDesignated = droolsPdpsElectionHandler.santizeDesignatedList(listOfDesignated); + + logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size after all designated = {}\n\n", + listOfDesignated.size()); + + assertTrue(listOfDesignated.size() == 4); + + } + + /** + * Test Compute most recent primary. + * + * @throws Exception exception + */ + //@Ignore + //@Test + public void testComputeMostRecentPrimary() throws Exception { + + logger.debug("\n\ntestComputeMostRecentPrimary: Entering\n\n"); + + Properties activeStandbyProperties = loadActiveStandbyProperties(); + + logger.debug("testComputeMostRecentPrimary: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + final DroolsPdpsConnector droolsPdpsConnector = new JpaDroolsPdpsConnector(emfDrools); + + + // Create 4 pdpd all not designated + + + long designatedDateMs = testTime.getMillis(); + DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, testTime.getDate()); + pdp1.setDesignatedDate(new Date(designatedDateMs - 2)); + + DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, testTime.getDate()); + //oldest + pdp2.setDesignatedDate(new Date(designatedDateMs - 3)); + + DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, testTime.getDate()); + pdp3.setDesignatedDate(new Date(designatedDateMs - 1)); + + DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, testTime.getDate()); + //most recent + pdp4.setDesignatedDate(new Date(designatedDateMs)); + + ArrayList listOfAllPdps = new ArrayList(); + listOfAllPdps.add(pdp1); + listOfAllPdps.add(pdp2); + listOfAllPdps.add(pdp3); + listOfAllPdps.add(pdp4); + + + ArrayList listOfDesignated = new ArrayList(); + listOfDesignated.add(pdp1); + listOfDesignated.add(pdp2); + listOfDesignated.add(pdp3); + listOfDesignated.add(pdp4); + + // Because the way we sanitize the listOfDesignated, it will always contain all hot standby + // or all designated members. + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureApi stateManagementFeature = null; + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + stateManagementFeature = feature; + logger.debug("testComputeMostRecentPrimary stateManagementFeature.getResourceName(): {}", + stateManagementFeature.getResourceName()); + break; + } + assertNotNull(stateManagementFeature); + + DroolsPdpsElectionHandler droolsPdpsElectionHandler = new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1); + + DroolsPdp mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary( + listOfAllPdps, listOfDesignated); + + logger.debug("\n\ntestComputeMostRecentPrimary: mostRecentPrimary.getPdpId() = {}\n\n", + mostRecentPrimary.getPdpId()); + + + // If all of the pdps are included in the listOfDesignated and none are designated, it will choose + // the one which has the most recent designated date. + + + assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); + + + // Now let's designate all of those on the listOfDesignated. It will choose the first one designated + + + pdp1.setDesignated(true); + pdp2.setDesignated(true); + pdp3.setDesignated(true); + pdp4.setDesignated(true); + + mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); + + logger.debug("\n\ntestComputeMostRecentPrimary: All designated all on list, " + + "mostRecentPrimary.getPdpId() = {}\n\n", + mostRecentPrimary.getPdpId()); + + + // If all of the pdps are included in the listOfDesignated and all are designated, it will choose + // the one which was designated first + + + assertTrue(mostRecentPrimary.getPdpId().equals("pdp2")); + + + // Now we will designate only 2 and put just them in the listOfDesignated. The algorithm will now + // look for the most recently designated pdp which is not currently designated. + + + pdp3.setDesignated(false); + pdp4.setDesignated(false); + + listOfDesignated.remove(pdp3); + listOfDesignated.remove(pdp4); + + mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); + + logger.debug("\n\ntestComputeMostRecentPrimary: mostRecentPrimary.getPdpId() = {}\n\n", + mostRecentPrimary.getPdpId()); + + assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); + + + + // Now we will have none designated and put two of them in the listOfDesignated. The algorithm will now + // look for the most recently designated pdp regardless of whether it is currently marked as designated. + + + pdp1.setDesignated(false); + pdp2.setDesignated(false); + + mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); + + logger.debug("\n\ntestComputeMostRecentPrimary: 2 on list mostRecentPrimary.getPdpId() = {}\n\n", + mostRecentPrimary.getPdpId()); + + assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); + + + // If we have only one pdp on in the listOfDesignated, + // the most recently designated pdp will be chosen, regardless + // of its designation status + + + listOfDesignated.remove(pdp1); + + mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); + + logger.debug("\n\ntestComputeMostRecentPrimary: 1 on list mostRecentPrimary.getPdpId() = {}\n\n", + mostRecentPrimary.getPdpId()); + + assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); + + + // Finally, if none are on the listOfDesignated, it will again choose the most recently designated pdp. + + + listOfDesignated.remove(pdp2); + + mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); + + logger.debug("\n\ntestComputeMostRecentPrimary: 0 on list mostRecentPrimary.getPdpId() = {}\n\n", + mostRecentPrimary.getPdpId()); + + assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); + + } + + /** + * Test compute designated PDP. + * + * @throws Exception exception + */ + //@Ignore + //@Test + public void testComputeDesignatedPdp() throws Exception { + + logger.debug("\n\ntestComputeDesignatedPdp: Entering\n\n"); + + Properties activeStandbyProperties = loadActiveStandbyProperties(); + + + logger.debug("testComputeDesignatedPdp: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + final DroolsPdpsConnector droolsPdpsConnector = new JpaDroolsPdpsConnector(emfDrools); + + + // Create 4 pdpd all not designated. Two on site1. Two on site2 + + + long designatedDateMs = testTime.getMillis(); + DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, testTime.getDate()); + pdp1.setDesignatedDate(new Date(designatedDateMs - 2)); + pdp1.setSite("site1"); + + DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, testTime.getDate()); + pdp2.setDesignatedDate(new Date(designatedDateMs - 3)); + pdp2.setSite("site1"); + + //oldest + DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, testTime.getDate()); + pdp3.setDesignatedDate(new Date(designatedDateMs - 4)); + pdp3.setSite("site2"); + + DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, testTime.getDate()); + //most recent + pdp4.setDesignatedDate(new Date(designatedDateMs)); + pdp4.setSite("site2"); + + ArrayList listOfAllPdps = new ArrayList(); + listOfAllPdps.add(pdp1); + listOfAllPdps.add(pdp2); + listOfAllPdps.add(pdp3); + listOfAllPdps.add(pdp4); + + + ArrayList listOfDesignated = new ArrayList(); + + + // We will first test an empty listOfDesignated. As we know from the previous JUnit, + // the pdp with the most designated date will be chosen for mostRecentPrimary + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureApi stateManagementFeature = null; + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + stateManagementFeature = feature; + logger.debug("testComputeDesignatedPdp stateManagementFeature.getResourceName(): {}", + stateManagementFeature.getResourceName()); + break; + } + assertNotNull(stateManagementFeature); + + + DroolsPdpsElectionHandler droolsPdpsElectionHandler = new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1); + + DroolsPdp mostRecentPrimary = pdp4; + + DroolsPdp designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary); + + + // The designatedPdp should be null + + assertTrue(designatedPdp == null); + + + // Now let's try having only one pdp in listOfDesignated, but not in the same site as the most recent primary + + listOfDesignated.add(pdp2); + + designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary); + + + // Now the designatedPdp should be the one and only selection in the listOfDesignated + + + assertTrue(designatedPdp.getPdpId().equals(pdp2.getPdpId())); + + + // Now let's put 2 pdps in the listOfDesignated, neither in the same site as the mostRecentPrimary + + + listOfDesignated.add(pdp1); + + designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary); + + + // The designatedPdp should now be the one with the lowest lexiographic score - pdp1 + + + assertTrue(designatedPdp.getPdpId().equals(pdp1.getPdpId())); + + + // Finally, we will have 2 pdps in the listOfDesignated, one in the same site with the mostRecentPrimary + + + listOfDesignated.remove(pdp1); + listOfDesignated.add(pdp3); + + designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary); + + + // The designatedPdp should now be the one on the same site as the mostRecentPrimary + + + assertTrue(designatedPdp.getPdpId().equals(pdp3.getPdpId())); + } + + /** + * Test cold standby. + * + * @throws Exception exception + */ + //@Ignore + //@Test + public void testColdStandby() throws Exception { + + logger.debug("\n\ntestColdStandby: Entering\n\n"); + cleanXacmlDb(); + cleanDroolsDb(); + + Properties stateManagementProperties = loadStateManagementProperties(); + + logger.debug("testColdStandby: Creating emfXacml"); + final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( + "junitXacmlPU", stateManagementProperties); + + Properties activeStandbyProperties = loadActiveStandbyProperties(); + final String thisPdpId = activeStandbyProperties.getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.debug("testColdStandby: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); + + logger.debug("testColdStandby: Cleaning up tables"); + conn.deleteAllPdps(); + + logger.debug("testColdStandby: Inserting PDP={} as designated", thisPdpId); + DroolsPdp pdp = new DroolsPdpImpl(thisPdpId, true, 4, testTime.getDate()); + conn.insertPdp(pdp); + DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testColdStandby: After insertion, DESIGNATED= {} " + + "for PDP= {}", droolsPdpEntity.isDesignated(), thisPdpId); + assertTrue(droolsPdpEntity.isDesignated() == true); + + /* + * When the Standby Status changes (from providingservice) to hotstandby + * or coldstandby,the Active/Standby selection algorithm must stand down + * if thePDP-D is currently the lead/active node and allow another PDP-D + * to take over. + * + * It must also call lock on all engines in the engine management. + */ + + + /* + * Yes, this is kludgy, but we have a chicken and egg problem here: we + * need a StateManagement object to invoke the + * deleteAllStateManagementEntities method. + */ + logger.debug("testColdStandby: Instantiating stateManagement object"); + + StateManagement sm = new StateManagement(emfXacml, "dummy"); + sm.deleteAllStateManagementEntities(); + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureApi smf = null; + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + smf = feature; + logger.debug("testColdStandby stateManagementFeature.getResourceName(): {}", smf.getResourceName()); + break; + } + assertNotNull(smf); + + // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature + // that has been created. + ActiveStandbyFeatureApi activeStandbyFeature = null; + for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + activeStandbyFeature = feature; + logger.debug("testColdStandby activeStandbyFeature.getResourceName(): {}", + activeStandbyFeature.getResourceName()); + break; + } + assertNotNull(activeStandbyFeature); + + // Artificially putting a PDP into service is really a two step process, 1) + // inserting it as designated and 2) promoting it so that its standbyStatus + // is providing service. + + logger.debug("testColdStandby: Runner started; Sleeping " + + INTERRUPT_RECOVERY_TIME + "ms before promoting PDP= {}", + thisPdpId); + sleep(INTERRUPT_RECOVERY_TIME); + + logger.debug("testColdStandby: Promoting PDP={}", thisPdpId); + smf.promote(); + + String standbyStatus = sm.getStandbyStatus(thisPdpId); + logger.debug("testColdStandby: Before locking, PDP= {} has standbyStatus= {}", + thisPdpId, standbyStatus); + + logger.debug("testColdStandby: Locking smf"); + smf.lock(); + + sleep(INTERRUPT_RECOVERY_TIME); + + // Verify that the PDP is no longer designated. + + droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testColdStandby: After lock sm.lock() invoked, " + + "DESIGNATED= {} for PDP={}", droolsPdpEntity.isDesignated(), thisPdpId); + assertTrue(droolsPdpEntity.isDesignated() == false); + + logger.debug("\n\ntestColdStandby: Exiting\n\n"); + sleep(INTERRUPT_RECOVERY_TIME); + + } + + // Tests hot standby when there is only one PDP. + + /** + * Test hot standby 1. + * + * @throws Exception exception + */ + //@Ignore + //@Test + public void testHotStandby1() throws Exception { + + logger.debug("\n\ntestHotStandby1: Entering\n\n"); + cleanXacmlDb(); + cleanDroolsDb(); + + Properties stateManagementProperties = loadStateManagementProperties(); + + logger.debug("testHotStandby1: Creating emfXacml"); + final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( + "junitXacmlPU", stateManagementProperties); + + Properties activeStandbyProperties = loadActiveStandbyProperties(); + final String thisPdpId = activeStandbyProperties + .getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.debug("testHotStandby1: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); + + logger.debug("testHotStandby1: Cleaning up tables"); + conn.deleteAllPdps(); + + /* + * Insert this PDP as not designated. Initial standby state will be + * either null or cold standby. Demoting should transit state to + * hot standby. + */ + + logger.debug("testHotStandby1: Inserting PDP={} as not designated", thisPdpId); + Date yesterday = DateUtils.addDays(testTime.getDate(), -1); + DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday); + conn.insertPdp(pdp); + DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testHotStandby1: After insertion, PDP={} has DESIGNATED={}", + thisPdpId, droolsPdpEntity.isDesignated()); + assertTrue(droolsPdpEntity.isDesignated() == false); + + logger.debug("testHotStandby1: Instantiating stateManagement object"); + StateManagement sm = new StateManagement(emfXacml, "dummy"); + sm.deleteAllStateManagementEntities(); + + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureApi smf = null; + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + smf = feature; + logger.debug("testHotStandby1 stateManagementFeature.getResourceName(): {}", smf.getResourceName()); + break; + } + assertNotNull(smf); + + // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature + // that has been created. + ActiveStandbyFeatureApi activeStandbyFeature = null; + for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + activeStandbyFeature = feature; + logger.debug("testHotStandby1 activeStandbyFeature.getResourceName(): {}", + activeStandbyFeature.getResourceName()); + break; + } + assertNotNull(activeStandbyFeature); + + + logger.debug("testHotStandby1: Demoting PDP={}", thisPdpId); + // demoting should cause state to transit to hotstandby + smf.demote(); + + + logger.debug("testHotStandby1: Sleeping {} ms, to allow JpaDroolsPdpsConnector " + + "time to check droolspdpentity table", SLEEP_TIME); + sleep(SLEEP_TIME); + + + // Verify that this formerly un-designated PDP in HOT_STANDBY is now designated and providing service. + + droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testHotStandby1: After sm.demote() invoked, DESIGNATED= {} " + + "for PDP= {}", droolsPdpEntity.isDesignated(), thisPdpId); + assertTrue(droolsPdpEntity.isDesignated() == true); + String standbyStatus = smf.getStandbyStatus(thisPdpId); + logger.debug("testHotStandby1: After demotion, PDP= {} " + + "has standbyStatus= {}", thisPdpId, standbyStatus); + assertTrue(standbyStatus != null && standbyStatus.equals(StateManagement.PROVIDING_SERVICE)); + + logger.debug("testHotStandby1: Stopping policyManagementRunner"); + + logger.debug("\n\ntestHotStandby1: Exiting\n\n"); + sleep(INTERRUPT_RECOVERY_TIME); + + } + + /* + * Tests hot standby when two PDPs are involved. + */ + + /** + * Test hot standby 2. + * + * @throws Exception exception + */ + //@Ignore + //@Test + public void testHotStandby2() throws Exception { + + logger.info("\n\ntestHotStandby2: Entering\n\n"); + cleanXacmlDb(); + cleanDroolsDb(); + + Properties stateManagementProperties = loadStateManagementProperties(); + + logger.info("testHotStandby2: Creating emfXacml"); + final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( + "junitXacmlPU", stateManagementProperties); + + Properties activeStandbyProperties = loadActiveStandbyProperties(); + final String thisPdpId = activeStandbyProperties + .getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.info("testHotStandby2: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); + + logger.info("testHotStandby2: Cleaning up tables"); + conn.deleteAllPdps(); + + + // Insert a PDP that's designated but not current. + + String activePdpId = "pdp2"; + logger.info("testHotStandby2: Inserting PDP={} as stale, designated PDP", activePdpId); + Date yesterday = DateUtils.addDays(testTime.getDate(), -1); + DroolsPdp pdp = new DroolsPdpImpl(activePdpId, true, 4, yesterday); + conn.insertPdp(pdp); + DroolsPdpEntity droolsPdpEntity = conn.getPdp(activePdpId); + logger.info("testHotStandby2: After insertion, PDP= {}, which is " + + "not current, has DESIGNATED= {}", activePdpId, droolsPdpEntity.isDesignated()); + assertTrue(droolsPdpEntity.isDesignated() == true); + + /* + * Promote the designated PDP. + * + * We have a chicken and egg problem here: we need a StateManagement + * object to invoke the deleteAllStateManagementEntities method. + */ + + + logger.info("testHotStandby2: Promoting PDP={}", activePdpId); + StateManagement sm = new StateManagement(emfXacml, "dummy"); + sm.deleteAllStateManagementEntities(); + + + sm = new StateManagement(emfXacml, activePdpId);//pdp2 + + // Artificially putting a PDP into service is really a two step process, 1) + // inserting it as designated and 2) promoting it so that its standbyStatus + // is providing service. + + /* + * Insert this PDP as not designated. Initial standby state will be + * either null or cold standby. Demoting should transit state to + * hot standby. + */ + + + logger.info("testHotStandby2: Inserting PDP= {} as not designated", thisPdpId); + pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday); + conn.insertPdp(pdp); + droolsPdpEntity = conn.getPdp(thisPdpId); + logger.info("testHotStandby2: After insertion, PDP={} " + + "has DESIGNATED= {}", thisPdpId, droolsPdpEntity.isDesignated()); + assertTrue(droolsPdpEntity.isDesignated() == false); + + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureApi sm2 = null; + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + sm2 = feature; + logger.debug("testHotStandby2 stateManagementFeature.getResourceName(): {}", sm2.getResourceName()); + break; + } + assertNotNull(sm2); + + // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature + // that has been created. + ActiveStandbyFeatureApi activeStandbyFeature = null; + for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + activeStandbyFeature = feature; + logger.debug("testHotStandby2 activeStandbyFeature.getResourceName(): {}", + activeStandbyFeature.getResourceName()); + break; + } + assertNotNull(activeStandbyFeature); + + logger.info("testHotStandby2: Runner started; Sleeping {} " + + "ms before promoting/demoting", INTERRUPT_RECOVERY_TIME); + sleep(INTERRUPT_RECOVERY_TIME); + + logger.info("testHotStandby2: Runner started; promoting PDP={}", activePdpId); + //At this point, the newly created pdp will have set the state to disabled/failed/cold standby + //because it is stale. So, it cannot be promoted. We need to call sm.enableNotFailed() so we + //can promote it and demote the other pdp - else the other pdp will just spring back to providingservice + sm.enableNotFailed();//pdp2 + sm.promote(); + String standbyStatus = sm.getStandbyStatus(activePdpId); + logger.info("testHotStandby2: After promoting, PDP= {} has standbyStatus= {}", activePdpId, standbyStatus); + + // demoting PDP should ensure that state transits to hotstandby + logger.info("testHotStandby2: Runner started; demoting PDP= {}", thisPdpId); + sm2.demote();//pdp1 + standbyStatus = sm.getStandbyStatus(thisPdpId); + logger.info("testHotStandby2: After demoting, PDP={} has standbyStatus= {}",thisPdpId , standbyStatus); + + logger.info("testHotStandby2: Sleeping {} ms, to allow JpaDroolsPdpsConnector " + + "time to check droolspdpentity table", SLEEP_TIME); + sleep(SLEEP_TIME); + + /* + * Verify that this PDP, demoted to HOT_STANDBY, is now + * re-designated and providing service. + */ + + droolsPdpEntity = conn.getPdp(thisPdpId); + logger.info("testHotStandby2: After demoting PDP={}" + + ", DESIGNATED= {}" + + " for PDP= {}", activePdpId, droolsPdpEntity.isDesignated(), thisPdpId); + assertTrue(droolsPdpEntity.isDesignated() == true); + standbyStatus = sm2.getStandbyStatus(thisPdpId); + logger.info("testHotStandby2: After demoting PDP={}" + + ", PDP={} has standbyStatus= {}", + activePdpId, thisPdpId, standbyStatus); + assertTrue(standbyStatus != null + && standbyStatus.equals(StateManagement.PROVIDING_SERVICE)); + + logger.info("testHotStandby2: Stopping policyManagementRunner"); + + logger.info("\n\ntestHotStandby2: Exiting\n\n"); + sleep(INTERRUPT_RECOVERY_TIME); + + } + + /* + * 1) Inserts and designates this PDP, then verifies that startTransaction + * is successful. + * + * 2) Demotes PDP, and verifies that because there is only one PDP, it will + * be immediately re-promoted, thus allowing startTransaction to be + * successful. + * + * 3) Locks PDP and verifies that startTransaction results in + * AdministrativeStateException. + * + * 4) Unlocks PDP and verifies that startTransaction results in + * StandbyStatusException. + * + * 5) Promotes PDP and verifies that startTransaction is once again + * successful. + */ + + /** + * Test locking. + * + * @throws Exception exception + */ + //@Ignore + //@Test + public void testLocking1() throws Exception { + logger.debug("testLocking1: Entry"); + cleanXacmlDb(); + cleanDroolsDb(); + + Properties stateManagementProperties = loadStateManagementProperties(); + + logger.debug("testLocking1: Creating emfXacml"); + final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( + "junitXacmlPU", stateManagementProperties); + + Properties activeStandbyProperties = loadActiveStandbyProperties(); + final String thisPdpId = activeStandbyProperties + .getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.debug("testLocking1: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); + + logger.debug("testLocking1: Cleaning up tables"); + conn.deleteAllPdps(); + + /* + * Insert this PDP as designated. Initial standby state will be + * either null or cold standby. + */ + + logger.debug("testLocking1: Inserting PDP= {} as designated", thisPdpId); + DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, true, 4, testTime.getDate()); + conn.insertPdp(pdp); + DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testLocking1: After insertion, PDP= {} has DESIGNATED= {}", + thisPdpId, droolsPdpEntity.isDesignated()); + assertTrue(droolsPdpEntity.isDesignated() == true); + + logger.debug("testLocking1: Instantiating stateManagement object"); + StateManagement smDummy = new StateManagement(emfXacml, "dummy"); + smDummy.deleteAllStateManagementEntities(); + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureApi sm = null; + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + sm = feature; + logger.debug("testLocking1 stateManagementFeature.getResourceName(): {}", sm.getResourceName()); + break; + } + assertNotNull(sm); + + // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature + // that has been created. + ActiveStandbyFeatureApi activeStandbyFeature = null; + for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + activeStandbyFeature = feature; + logger.debug("testLocking1 activeStandbyFeature.getResourceName(): {}", + activeStandbyFeature.getResourceName()); + break; + } + assertNotNull(activeStandbyFeature); + + logger.debug("testLocking1: Runner started; Sleeping " + + INTERRUPT_RECOVERY_TIME + "ms before promoting PDP={}", + thisPdpId); + sleep(INTERRUPT_RECOVERY_TIME); + + logger.debug("testLocking1: Promoting PDP={}", thisPdpId); + sm.promote(); + + logger.debug("testLocking1: Sleeping {} ms, to allow time for " + + "policy-management.Main class to come up, designated= {}", + SLEEP_TIME, conn.getPdp(thisPdpId).isDesignated()); + sleep(SLEEP_TIME); + + logger.debug("testLocking1: Waking up and invoking startTransaction on active PDP={}" + + ", designated= {}",thisPdpId, conn.getPdp(thisPdpId).isDesignated()); + + + IntegrityMonitor droolsPdpIntegrityMonitor = IntegrityMonitor.getInstance(); + try { + droolsPdpIntegrityMonitor.startTransaction(); + droolsPdpIntegrityMonitor.endTransaction(); + logger.debug("testLocking1: As expected, transaction successful"); + } catch (AdministrativeStateException e) { + logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, ", e); + assertTrue(false); + } catch (StandbyStatusException e) { + logger.error("testLocking1: Unexpectedly caught StandbyStatusException, ", e); + assertTrue(false); + } catch (Exception e) { + logger.error("testLocking1: Unexpectedly caught Exception, ", e); + assertTrue(false); + } + + // demoting should cause state to transit to hotstandby, followed by re-promotion, + // since there is only one PDP. + logger.debug("testLocking1: demoting PDP={}", thisPdpId); + sm.demote(); + + logger.debug("testLocking1: sleeping" + ELECTION_WAIT_SLEEP_TIME + + " to allow election handler to re-promote PDP={}", thisPdpId); + sleep(ELECTION_WAIT_SLEEP_TIME); + + logger.debug("testLocking1: Invoking startTransaction on re-promoted PDP={}" + + ", designated={}", thisPdpId, conn.getPdp(thisPdpId).isDesignated()); + try { + droolsPdpIntegrityMonitor.startTransaction(); + droolsPdpIntegrityMonitor.endTransaction(); + logger.debug("testLocking1: As expected, transaction successful"); + } catch (AdministrativeStateException e) { + logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, ", e); + assertTrue(false); + } catch (StandbyStatusException e) { + logger.error("testLocking1: Unexpectedly caught StandbyStatusException, ", e); + assertTrue(false); + } catch (Exception e) { + logger.error("testLocking1: Unexpectedly caught Exception, ", e); + assertTrue(false); + } + + // locking should cause state to transit to cold standby + logger.debug("testLocking1: locking PDP={}", thisPdpId); + sm.lock(); + + // Just to avoid any race conditions, sleep a little after locking + logger.debug("testLocking1: Sleeping a few millis after locking, to avoid race condition"); + sleep(100); + + logger.debug("testLocking1: Invoking startTransaction on locked PDP= {}" + + ", designated= {}",thisPdpId, conn.getPdp(thisPdpId).isDesignated()); + try { + droolsPdpIntegrityMonitor.startTransaction(); + logger.error("testLocking1: startTransaction unexpectedly successful"); + assertTrue(false); + } catch (AdministrativeStateException e) { + logger.debug("testLocking1: As expected, caught AdministrativeStateException, ", e); + } catch (StandbyStatusException e) { + logger.error("testLocking1: Unexpectedly caught StandbyStatusException, ", e); + assertTrue(false); + } catch (Exception e) { + logger.error("testLocking1: Unexpectedly caught Exception, ", e); + assertTrue(false); + } finally { + droolsPdpIntegrityMonitor.endTransaction(); + } + + // unlocking should cause state to transit to hot standby and then providing service + logger.debug("testLocking1: unlocking PDP={}", thisPdpId); + sm.unlock(); + + // Just to avoid any race conditions, sleep a little after locking + logger.debug("testLocking1: Sleeping a few millis after unlocking, to avoid race condition"); + sleep(ELECTION_WAIT_SLEEP_TIME); + + logger.debug("testLocking1: Invoking startTransaction on unlocked PDP=" + + thisPdpId + + ", designated=" + + conn.getPdp(thisPdpId).isDesignated()); + try { + droolsPdpIntegrityMonitor.startTransaction(); + logger.error("testLocking1: startTransaction successful as expected"); + } catch (AdministrativeStateException e) { + logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, ", e); + assertTrue(false); + } catch (StandbyStatusException e) { + logger.debug("testLocking1: Unexpectedly caught StandbyStatusException, ", e); + assertTrue(false); + } catch (Exception e) { + logger.error("testLocking1: Unexpectedly caught Exception, ", e); + assertTrue(false); + } finally { + droolsPdpIntegrityMonitor.endTransaction(); + } + + // demoting should cause state to transit to hot standby + logger.debug("testLocking1: demoting PDP={}", thisPdpId); + sm.demote(); + + // Just to avoid any race conditions, sleep a little after promoting + logger.debug("testLocking1: Sleeping a few millis after demoting, to avoid race condition"); + sleep(100); + + logger.debug("testLocking1: Invoking startTransaction on demoted PDP={}" + + ", designated={}", thisPdpId, conn.getPdp(thisPdpId).isDesignated()); + try { + droolsPdpIntegrityMonitor.startTransaction(); + droolsPdpIntegrityMonitor.endTransaction(); + logger.debug("testLocking1: Unexpectedly, transaction successful"); + assertTrue(false); + } catch (AdministrativeStateException e) { + logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, ", e); + assertTrue(false); + } catch (StandbyStatusException e) { + logger.error("testLocking1: As expected caught StandbyStatusException, ", e); + } catch (Exception e) { + logger.error("testLocking1: Unexpectedly caught Exception, ", e); + assertTrue(false); + } + + logger.debug("\n\ntestLocking1: Exiting\n\n"); + sleep(INTERRUPT_RECOVERY_TIME); + + } + + + /* + * 1) Inserts and designates this PDP, then verifies that startTransaction + * is successful. + * + * 2) Inserts another PDP in hotstandby. + * + * 3) Demotes this PDP, and verifies 1) that other PDP is not promoted (because one + * PDP cannot promote another PDP) and 2) that this PDP is re-promoted. + */ + + /** + * Test locking 2. + * + * @throws Exception exception + */ + //@Ignore + //@Test + public void testLocking2() throws Exception { + + logger.debug("\n\ntestLocking2: Entering\n\n"); + cleanXacmlDb(); + cleanDroolsDb(); + + Properties stateManagementProperties = loadStateManagementProperties(); + + logger.debug("testLocking2: Creating emfXacml"); + final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( + "junitXacmlPU", stateManagementProperties); + + Properties activeStandbyProperties = loadActiveStandbyProperties(); + final String thisPdpId = activeStandbyProperties + .getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.debug("testLocking2: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); + + logger.debug("testLocking2: Cleaning up tables"); + conn.deleteAllPdps(); + + /* + * Insert this PDP as designated. Initial standby state will be + * either null or cold standby. Demoting should transit state to + * hot standby. + */ + + logger.debug("testLocking2: Inserting PDP= {} as designated", thisPdpId); + DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, true, 3, testTime.getDate()); + conn.insertPdp(pdp); + DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testLocking2: After insertion, PDP= {} has DESIGNATED= {}", + thisPdpId, droolsPdpEntity.isDesignated()); + assertTrue(droolsPdpEntity.isDesignated() == true); + + logger.debug("testLocking2: Instantiating stateManagement object and promoting PDP={}", thisPdpId); + StateManagement smDummy = new StateManagement(emfXacml, "dummy"); + smDummy.deleteAllStateManagementEntities(); + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureApi sm = null; + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + sm = feature; + logger.debug("testLocking2 stateManagementFeature.getResourceName(): {}", sm.getResourceName()); + break; + } + assertNotNull(sm); + + // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature + // that has been created. + ActiveStandbyFeatureApi activeStandbyFeature = null; + for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { + ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR); + activeStandbyFeature = feature; + logger.debug("testLocking2 activeStandbyFeature.getResourceName(): {}", + activeStandbyFeature.getResourceName()); + break; + } + assertNotNull(activeStandbyFeature); + + /* + * Insert another PDP as not designated. Initial standby state will be + * either null or cold standby. Demoting should transit state to + * hot standby. + */ + + String standbyPdpId = "pdp2"; + logger.debug("testLocking2: Inserting PDP= {} as not designated", standbyPdpId); + Date yesterday = DateUtils.addDays(testTime.getDate(), -1); + pdp = new DroolsPdpImpl(standbyPdpId, false, 4, yesterday); + conn.insertPdp(pdp); + droolsPdpEntity = conn.getPdp(standbyPdpId); + logger.debug("testLocking2: After insertion, PDP={} has DESIGNATED= {}", + standbyPdpId, droolsPdpEntity.isDesignated()); + assertTrue(droolsPdpEntity.isDesignated() == false); + + logger.debug("testLocking2: Demoting PDP= {}", standbyPdpId); + final StateManagement sm2 = new StateManagement(emfXacml, standbyPdpId); + + logger.debug("testLocking2: Runner started; Sleeping {} ms " + + "before promoting/demoting", INTERRUPT_RECOVERY_TIME); + sleep(INTERRUPT_RECOVERY_TIME); + + logger.debug("testLocking2: Promoting PDP= {}", thisPdpId); + sm.promote(); + + // demoting PDP should ensure that state transits to hotstandby + logger.debug("testLocking2: Demoting PDP={}", standbyPdpId); + sm2.demote(); + + logger.debug("testLocking2: Sleeping {} ms, to allow time for to come up", SLEEP_TIME); + sleep(SLEEP_TIME); + + logger.debug("testLocking2: Waking up and invoking startTransaction on active PDP={}" + + ", designated= {}", thisPdpId, conn.getPdp(thisPdpId).isDesignated()); + + IntegrityMonitor droolsPdpIntegrityMonitor = IntegrityMonitor.getInstance(); + + try { + droolsPdpIntegrityMonitor.startTransaction(); + droolsPdpIntegrityMonitor.endTransaction(); + logger.debug("testLocking2: As expected, transaction successful"); + } catch (AdministrativeStateException e) { + logger.error("testLocking2: Unexpectedly caught AdministrativeStateException, ", e); + assertTrue(false); + } catch (StandbyStatusException e) { + logger.error("testLocking2: Unexpectedly caught StandbyStatusException, ", e); + assertTrue(false); + } catch (Exception e) { + logger.error("testLocking2: Unexpectedly caught Exception, ", e); + assertTrue(false); + } + + // demoting should cause state to transit to hotstandby followed by re-promotion. + logger.debug("testLocking2: demoting PDP={}", thisPdpId); + sm.demote(); + + logger.debug("testLocking2: sleeping {}" + + " to allow election handler to re-promote PDP={}", ELECTION_WAIT_SLEEP_TIME, thisPdpId); + sleep(ELECTION_WAIT_SLEEP_TIME); + + logger.debug("testLocking2: Waking up and invoking startTransaction " + + "on re-promoted PDP= {}, designated= {}", + thisPdpId, conn.getPdp(thisPdpId).isDesignated()); + try { + droolsPdpIntegrityMonitor.startTransaction(); + droolsPdpIntegrityMonitor.endTransaction(); + logger.debug("testLocking2: As expected, transaction successful"); + } catch (AdministrativeStateException e) { + logger.error("testLocking2: Unexpectedly caught AdministrativeStateException, ", e); + assertTrue(false); + } catch (StandbyStatusException e) { + logger.error("testLocking2: Unexpectedly caught StandbyStatusException, ", e); + assertTrue(false); + } catch (Exception e) { + logger.error("testLocking2: Unexpectedly caught Exception, ", e); + assertTrue(false); + } + + logger.debug("testLocking2: Verifying designated status for PDP= {}", standbyPdpId); + boolean standbyPdpDesignated = conn.getPdp(standbyPdpId).isDesignated(); + assertTrue(standbyPdpDesignated == false); + + logger.debug("\n\ntestLocking2: Exiting\n\n"); + sleep(INTERRUPT_RECOVERY_TIME); + } + + private static Properties loadStateManagementProperties() throws IOException { + try (FileInputStream input = new FileInputStream(CONFIG_DIR + "/feature-state-management.properties")) { + Properties props = new Properties(); + props.load(input); + return props; + } + } + + private static Properties loadActiveStandbyProperties() throws IOException { + try (FileInputStream input = + new FileInputStream(CONFIG_DIR + "/feature-active-standby-management.properties")) { + Properties props = new Properties(); + props.load(input); + return props; + } + } + + private void sleep(long sleepms) throws InterruptedException { + testTime.waitFor(sleepms); + } +} diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java deleted file mode 100644 index 5e9b360f..00000000 --- a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * feature-active-standby-management - * ================================================================================ - * Copyright (C) 2017-2019 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.onap.policy.drools.controller.test; - -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.util.Date; -import java.util.Properties; -import java.util.function.Supplier; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; -import org.apache.commons.lang3.time.DateUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.common.im.StateManagement; -import org.onap.policy.drools.activestandby.ActiveStandbyFeatureApi; -import org.onap.policy.drools.activestandby.ActiveStandbyFeatureApiConstants; -import org.onap.policy.drools.activestandby.ActiveStandbyProperties; -import org.onap.policy.drools.activestandby.DroolsPdpEntity; -import org.onap.policy.drools.activestandby.DroolsPdpImpl; -import org.onap.policy.drools.activestandby.DroolsPdpsConnector; -import org.onap.policy.drools.activestandby.DroolsPdpsElectionHandler; -import org.onap.policy.drools.activestandby.JpaDroolsPdpsConnector; -import org.onap.policy.drools.core.PolicySessionFeatureApi; -import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; -import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/* - * Testing the allSeemsWell interface to verify that it correctly affects the - * operational state. - */ - -public class AllSeemsWellTest { - private static final Logger logger = LoggerFactory.getLogger(AllSeemsWellTest.class); - /* - * Currently, the DroolsPdpsElectionHandler.DesignationWaiter is invoked every 1 seconds, starting - * at the start of the next multiple of pdpUpdateInterval, but with a minimum of 5 sec cushion - * to ensure that we wait for the DesignationWaiter to do its job, before - * checking the results. Add a few seconds for safety - */ - - private static int SLEEP_TIME_SEC = 10; - - /* - * DroolsPdpsElectionHandler runs every 1 seconds, so it takes 10 seconds for the - * checkWaitTimer() method to time out and call allSeemsWell which then requires - * the forward progress counter to go stale which should add an additional 5 sec. - */ - - private static int STALLED_ELECTION_HANDLER_SLEEP_TIME_SEC = 15; - - /* - * As soon as the election hander successfully runs, it will resume the forward progress. - * If the election handler runs ever 1 sec and test transaction is run every 1 sec and - * then fpc is written every 1 sec and then the fpc is checked every 2 sec, that could - * take a total of 5 sec to recognize the resumption of progress. So, add 1 for safety. - */ - private static int RESUMED_ELECTION_HANDLER_SLEEP_TIME_SEC = 6; - - private static EntityManagerFactory emfx; - private static EntityManagerFactory emfd; - private static EntityManager emx; - private static EntityManager emd; - private static EntityTransaction et; - - private final String configDir = "src/test/resources/asw"; - - /* - * See the IntegrityMonitor.getJmxUrl() method for the rationale behind this jmx related processing. - */ - - /** - * Setup the class. - * - * @throws Exception exception - */ - @BeforeClass - public static void setUpClass() throws Exception { - - String userDir = System.getProperty("user.dir"); - logger.debug("setUpClass: userDir={}", userDir); - System.setProperty("com.sun.management.jmxremote.port", "9980"); - System.setProperty("com.sun.management.jmxremote.authenticate","false"); - } - - @AfterClass - public static void tearDownClass() throws Exception { - } - - /** - * Setup. - * - * @throws Exception exception - */ - @Before - public void setUp() throws Exception { - //Create teh data access for xaml db - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); - - emfx = Persistence.createEntityManagerFactory("junitXacmlPU", stateManagementProperties); - - // Create an entity manager to use the DB - emx = emfx.createEntityManager(); - - //Create the data access for drools db - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - - emfd = Persistence.createEntityManagerFactory("junitDroolsPU", activeStandbyProperties); - - // Create an entity manager to use the DB - emd = emfd.createEntityManager(); - - DroolsPdpsElectionHandler.setIsUnitTesting(true); - } - - @After - public void tearDown() throws Exception { - - } - - /** - * Clean the xacml database. - */ - public void cleanXacmlDb() { - et = emx.getTransaction(); - - et.begin(); - // Make sure we leave the DB clean - emx.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); - emx.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); - emx.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); - emx.flush(); - et.commit(); - } - - /** - * Clean the drools database. - */ - public void cleanDroolsDb() { - et = emd.getTransaction(); - - et.begin(); - // Make sure we leave the DB clean - emd.createQuery("DELETE FROM DroolsPdpEntity").executeUpdate(); - emd.flush(); - et.commit(); - } - - - // Tests hot standby when there is only one PDP. - - //@Ignore - @Test - public void testAllSeemsWell() throws Exception { - - logger.debug("\n\ntestAllSeemsWell: Entering\n\n"); - cleanXacmlDb(); - cleanDroolsDb(); - - logger.debug("testAllSeemsWell: Reading stateManagementProperties"); - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); - - logger.debug("testAllSeemsWell: Creating emfXacml"); - final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( - "junitXacmlPU", stateManagementProperties); - - logger.debug("testAllSeemsWell: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - final String thisPdpId = activeStandbyProperties - .getProperty(ActiveStandbyProperties.NODE_NAME); - - logger.debug("testAllSeemsWell: Creating emfDrools"); - EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( - "junitDroolsPU", activeStandbyProperties); - - DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); - - logger.debug("testAllSeemsWell: Cleaning up tables"); - conn.deleteAllPdps(); - - /* - * Insert this PDP as not designated. Initial standby state will be - * either null or cold standby. Demoting should transit state to - * hot standby. - */ - - logger.debug("testAllSeemsWell: Inserting PDP={} as not designated", thisPdpId); - Date yesterday = DateUtils.addDays(new Date(), -1); - DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday); - conn.insertPdp(pdp); - DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); - logger.debug("testAllSeemsWell: After insertion, PDP={} has DESIGNATED={}", - thisPdpId, droolsPdpEntity.isDesignated()); - assertTrue(droolsPdpEntity.isDesignated() == false); - - logger.debug("testAllSeemsWell: Instantiating stateManagement object"); - StateManagement sm = new StateManagement(emfXacml, "dummy"); - sm.deleteAllStateManagementEntities(); - - - // Now we want to create a StateManagementFeature and initialize it. It will be - // discovered by the ActiveStandbyFeature when the election handler initializes. - - StateManagementFeatureApi stateManagementFeatureApi = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - stateManagementFeatureApi = feature; - logger.debug("testAllSeemsWell stateManagementFeature.getResourceName(): {}", - stateManagementFeatureApi.getResourceName()); - break; - } - if (stateManagementFeatureApi == null) { - logger.error("testAllSeemsWell failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testAllSeemsWell failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } - final StateManagementFeatureApi smf = stateManagementFeatureApi; - - // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature - // that has been created. - ActiveStandbyFeatureApi activeStandbyFeature = null; - for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - activeStandbyFeature = feature; - logger.debug("testAllSeemsWell activeStandbyFeature.getResourceName(): {}", - activeStandbyFeature.getResourceName()); - break; - } - if (activeStandbyFeature == null) { - logger.error("testAllSeemsWell failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - logger.debug("testAllSeemsWell failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - } - - - logger.debug("testAllSeemsWell: Demoting PDP={}", thisPdpId); - // demoting should cause state to transit to hotstandby - smf.demote(); - - - logger.debug("testAllSeemsWell: Sleeping {} s, to allow JpaDroolsPdpsConnector " - + "time to check droolspdpentity table", SLEEP_TIME_SEC); - waitForCondition(() -> conn.getPdp(thisPdpId).isDesignated(), SLEEP_TIME_SEC); - - // Verify that this formerly un-designated PDP in HOT_STANDBY is now designated and providing service. - - droolsPdpEntity = conn.getPdp(thisPdpId); - logger.debug("testAllSeemsWell: After sm.demote() invoked, DESIGNATED= {} " - + "for PDP= {}", droolsPdpEntity.isDesignated(), thisPdpId); - assertTrue(droolsPdpEntity.isDesignated() == true); - String standbyStatus = smf.getStandbyStatus(thisPdpId); - logger.debug("testAllSeemsWell: After demotion, PDP= {} " - + "has standbyStatus= {}", thisPdpId, standbyStatus); - assertTrue(standbyStatus != null && standbyStatus.equals(StateManagement.PROVIDING_SERVICE)); - - //Now we want to stall the election handler and see the if AllSeemsWell will make the - //standbystatus = coldstandby - - DroolsPdpsElectionHandler.setIsStalled(true); - - logger.debug("testAllSeemsWell: Sleeping {} s, to allow checkWaitTimer to recognize " - + "the election handler has stalled and for the testTransaction to fail to " - + "increment forward progress and for the lack of forward progress to be recognized.", - STALLED_ELECTION_HANDLER_SLEEP_TIME_SEC); - - - //It takes 10x the update interval (1 sec) before the watcher will declare the election handler dead - //and that just stops forward progress counter. So, the fp monitor must then run to determine - // if the fpc has stalled. That will take about another 5 sec. - waitForCondition(() -> smf.getStandbyStatus().equals(StateManagement.COLD_STANDBY), - STALLED_ELECTION_HANDLER_SLEEP_TIME_SEC); - - logger.debug("testAllSeemsWell: After isStalled=true, PDP= {} " - + "has standbyStatus= {}", thisPdpId, smf.getStandbyStatus(thisPdpId)); - - assertTrue(smf.getStandbyStatus().equals(StateManagement.COLD_STANDBY)); - - //Now lets resume the election handler - DroolsPdpsElectionHandler.setIsStalled(false); - - waitForCondition(() -> smf.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE), - RESUMED_ELECTION_HANDLER_SLEEP_TIME_SEC); - - logger.debug("testAllSeemsWell: After isStalled=false, PDP= {} " - + "has standbyStatus= {}", thisPdpId, smf.getStandbyStatus(thisPdpId)); - - assertTrue(smf.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); - - //resumedElectionHandlerSleepTime = 5000; - logger.debug("\n\ntestAllSeemsWell: Exiting\n\n"); - - } - - private void waitForCondition(Supplier testCondition, int timeoutInSeconds) throws InterruptedException { - int maxIterations = timeoutInSeconds * 10; - int iterations = 0; - while (!testCondition.get() && iterations < maxIterations) { - iterations++; - Thread.sleep(100); - } - } -} diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/StandbyStateManagementTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/StandbyStateManagementTest.java deleted file mode 100644 index 8bc8489a..00000000 --- a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/StandbyStateManagementTest.java +++ /dev/null @@ -1,1615 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * feature-active-standby-management - * ================================================================================ - * Copyright (C) 2017-2019 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.onap.policy.drools.controller.test; - -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Properties; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; - -import org.apache.commons.lang3.time.DateUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.common.im.AdministrativeStateException; -import org.onap.policy.common.im.IntegrityMonitor; -import org.onap.policy.common.im.StandbyStatusException; -import org.onap.policy.common.im.StateManagement; -import org.onap.policy.drools.activestandby.ActiveStandbyFeatureApi; -import org.onap.policy.drools.activestandby.ActiveStandbyFeatureApiConstants; -import org.onap.policy.drools.activestandby.ActiveStandbyProperties; -import org.onap.policy.drools.activestandby.DroolsPdp; -import org.onap.policy.drools.activestandby.DroolsPdpEntity; -import org.onap.policy.drools.activestandby.DroolsPdpImpl; -import org.onap.policy.drools.activestandby.DroolsPdpsConnector; -import org.onap.policy.drools.activestandby.DroolsPdpsElectionHandler; -import org.onap.policy.drools.activestandby.JpaDroolsPdpsConnector; -import org.onap.policy.drools.activestandby.PmStandbyStateChangeNotifier; -import org.onap.policy.drools.core.PolicySessionFeatureApi; -import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; -import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/* - * All JUnits are designed to run in the local development environment - * where they have write privileges and can execute time-sensitive - * tasks. - * - * These tests can be run as JUnits, but there is some issue with running them - * as part of a "mvn install" build. Also, they take a very long time to run - * due to many real time breaks. Consequently, they are marked as @Ignore and - * only run from the desktop. - */ - -public class StandbyStateManagementTest { - private static final Logger logger = LoggerFactory.getLogger(StandbyStateManagementTest.class); - /* - * Currently, the DroolsPdpsElectionHandler.DesignationWaiter is invoked every 1 seconds, starting - * at the start of the next multiple of pdpUpdateInterval, but with a minimum of 5 sec cushion - * to ensure that we wait for the DesignationWaiter to do its job, before - * checking the results. Add a few seconds for safety - */ - - long sleepTime = 10000; - - /* - * DroolsPdpsElectionHandler runs every 1 seconds, so a 6 second sleep should be - * plenty to ensure it has time to re-promote this PDP. - */ - - long electionWaitSleepTime = 6000; - - /* - * Sleep 1 seconds after each test to allow interrupt (shutdown) recovery. - */ - - long interruptRecoveryTime = 5000; - - private static EntityManagerFactory emfx; - private static EntityManagerFactory emfd; - private static EntityManager emx; - private static EntityManager emd; - private static EntityTransaction et; - - private final String configDir = "src/test/resources"; - - /* - * See the IntegrityMonitor.getJmxUrl() method for the rationale behind this jmx related processing. - */ - - /** - * Setup the class. - * - * @throws Exception exception - */ - @BeforeClass - public static void setUpClass() throws Exception { - - String userDir = System.getProperty("user.dir"); - logger.debug("setUpClass: userDir={}", userDir); - System.setProperty("com.sun.management.jmxremote.port", "9980"); - System.setProperty("com.sun.management.jmxremote.authenticate","false"); - - } - - @AfterClass - public static void tearDownClass() throws Exception { - } - - /** - * Setup. - * - * @throws Exception exception - */ - @Before - public void setUp() throws Exception { - //Create teh data access for xaml db - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - "src/test/resources/feature-state-management.properties"))); - - emfx = Persistence.createEntityManagerFactory("junitXacmlPU", stateManagementProperties); - - // Create an entity manager to use the DB - emx = emfx.createEntityManager(); - - //Create the data access for drools db - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - "src/test/resources/feature-active-standby-management.properties"))); - - emfd = Persistence.createEntityManagerFactory("junitDroolsPU", activeStandbyProperties); - - // Create an entity manager to use the DB - emd = emfd.createEntityManager(); - } - - @After - public void tearDown() throws Exception { - - } - - /** - * Clean up the xacml database. - * - */ - public void cleanXacmlDb() { - et = emx.getTransaction(); - - et.begin(); - // Make sure we leave the DB clean - emx.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); - emx.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); - emx.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); - emx.flush(); - et.commit(); - } - - /** - * Clean up the drools db. - */ - public void cleanDroolsDb() { - et = emd.getTransaction(); - - et.begin(); - // Make sure we leave the DB clean - emd.createQuery("DELETE FROM DroolsPdpEntity").executeUpdate(); - emd.flush(); - et.commit(); - } - - /* - * These JUnit tests must be run one at a time in an eclipse environment - * by right-clicking StandbyStateManagementTest and selecting - * "Run As" -> "JUnit Test". - * - * They will run successfully when you run all of them under runAllTests(), - * however, you will get all sorts of non-fatal errors in the log and on the - * console that result from overlapping threads that are not terminated at the - * end of each test. The problem is that the JUnit environment does not terminate - * all the test threads between tests. This is true even if you break each JUnit - * into a separate file. Consequently, all the tests would have to be refactored - * so all test object initializations are coordinated. In other words, you - * retrieve the ActiveStandbyFeature instance and other class instances only once - * at the beginning of the JUnits and then reuse them throughout the tests. - * Initialization of the state of the objects is pretty straight forward as it - * just amounts to manipulating the entries in StateManagementEntity and - * DroolsPdpEntity tables. However, some thought needs to be given to how to - * "pause" the processing in ActiveStandbyFeature class. I think we could "pause" - * it by calling globalInit() which will, I think, restart it. So long as it - * does not create a new instance, it will force it to go through an initialization - * cycle which includes a "pause" at the beginning of proecessing. We just must - * be sure it does not create another instance - which may mean we need to add - * a factory interface instead of calling the constructor directly. - */ - - - //@Ignore - @Test - public void runAllTests() throws Exception { - testColdStandby(); - testHotStandby1(); - testHotStandby2(); - testLocking1(); - testLocking2(); - testPmStandbyStateChangeNotifier(); - testSanitizeDesignatedList(); - testComputeMostRecentPrimary(); - testComputeDesignatedPdp(); - } - - /** - * Test the standby state change notifier. - * - * @throws Exception exception - */ - //@Ignore - //@Test - public void testPmStandbyStateChangeNotifier() throws Exception { - logger.debug("\n\ntestPmStandbyStateChangeNotifier: Entering\n\n"); - cleanXacmlDb(); - - logger.debug("testPmStandbyStateChangeNotifier: Reading activeStandbyProperties"); - - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - - String resourceName = "testPMS"; - activeStandbyProperties.setProperty("resource.name", resourceName); - ActiveStandbyProperties.initProperties(activeStandbyProperties); - - logger.debug("testPmStandbyStateChangeNotifier: Getting StateManagement instance"); - - StateManagement sm = new StateManagement(emfx, resourceName); - - //Create an instance of the Observer - PmStandbyStateChangeNotifier pmNotifier = new PmStandbyStateChangeNotifier(); - - //Register the PmStandbyStateChangeNotifier Observer - sm.addObserver(pmNotifier); - - //At this point the standbystatus = 'null' - sm.lock(); - assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.NULL_VALUE)); - - sm.unlock(); - assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.NULL_VALUE)); - - //Adding standbystatus=hotstandby - sm.demote(); - System.out.println(pmNotifier.getPreviousStandbyStatus()); - assertTrue(pmNotifier.getPreviousStandbyStatus().equals( - PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); - - //Now making standbystatus=coldstandby - sm.lock(); - assertTrue(pmNotifier.getPreviousStandbyStatus().equals( - PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); - - //standbystatus = hotstandby - sm.unlock(); - assertTrue(pmNotifier.getPreviousStandbyStatus().equals( - PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); - - //standbystatus = providingservice - sm.promote(); - //The previousStandbyStatus is not updated until after the delay activation expires - assertTrue(pmNotifier.getPreviousStandbyStatus().equals( - PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); - - //Sleep long enough for the delayActivationTimer to run - sleep(5000); - assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); - - //standbystatus = providingservice - sm.promote(); - assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); - - //standbystatus = coldstandby - sm.lock(); - assertTrue(pmNotifier.getPreviousStandbyStatus().equals( - PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); - - //standbystatus = hotstandby - sm.unlock(); - assertTrue(pmNotifier.getPreviousStandbyStatus().equals( - PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); - - //standbystatus = hotstandby - sm.demote(); - assertTrue(pmNotifier.getPreviousStandbyStatus().equals( - PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); - } - - /** - * Test sanitize designated list. - * - * @throws Exception exception - */ - //@Ignore - //@Test - public void testSanitizeDesignatedList() throws Exception { - - logger.debug("\n\ntestSanitizeDesignatedList: Entering\n\n"); - - // Get a DroolsPdpsConnector - - logger.debug("testSanitizeDesignatedList: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - String thisPdpId = activeStandbyProperties - .getProperty(ActiveStandbyProperties.NODE_NAME); - - logger.debug("testSanitizeDesignatedList: Creating emfDrools"); - EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( - "junitDroolsPU", activeStandbyProperties); - - final DroolsPdpsConnector droolsPdpsConnector = new JpaDroolsPdpsConnector(emfDrools); - - // Create 4 pdpd all not designated - - DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, new Date()); - DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, new Date()); - DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, new Date()); - DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, new Date()); - - List listOfDesignated = new ArrayList(); - listOfDesignated.add(pdp1); - listOfDesignated.add(pdp2); - listOfDesignated.add(pdp3); - listOfDesignated.add(pdp4); - - // Now we want to create a StateManagementFeature and initialize it. It will be - // discovered by the ActiveStandbyFeature when the election handler initializes. - - StateManagementFeatureApi stateManagementFeature = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - stateManagementFeature = feature; - logger.debug("testColdStandby stateManagementFeature.getResourceName(): {}", - stateManagementFeature.getResourceName()); - break; - } - if (stateManagementFeature == null) { - logger.error("testColdStandby failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testColdStandby failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } - - - DroolsPdpsElectionHandler droolsPdpsElectionHandler = new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1); - - listOfDesignated = droolsPdpsElectionHandler.santizeDesignatedList(listOfDesignated); - - logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size = {}\n\n",listOfDesignated.size()); - - assertTrue(listOfDesignated.size() == 4); - - // Now make 2 designated - - pdp1.setDesignated(true); - pdp2.setDesignated(true); - - listOfDesignated = droolsPdpsElectionHandler.santizeDesignatedList(listOfDesignated); - - logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size after 2 designated = {}\n\n", - listOfDesignated.size()); - - assertTrue(listOfDesignated.size() == 2); - assertTrue(listOfDesignated.contains(pdp1)); - assertTrue(listOfDesignated.contains(pdp2)); - - - // Now all are designated. But, we have to add back the previously non-designated nodes - - pdp3.setDesignated(true); - pdp4.setDesignated(true); - listOfDesignated.add(pdp3); - listOfDesignated.add(pdp4); - - listOfDesignated = droolsPdpsElectionHandler.santizeDesignatedList(listOfDesignated); - - logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size after all designated = {}\n\n", - listOfDesignated.size()); - - assertTrue(listOfDesignated.size() == 4); - - } - - /** - * Test Compute most recent primary. - * - * @throws Exception exception - */ - //@Ignore - //@Test - public void testComputeMostRecentPrimary() throws Exception { - - logger.debug("\n\ntestComputeMostRecentPrimary: Entering\n\n"); - - logger.debug("testComputeMostRecentPrimary: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - String thisPdpId = activeStandbyProperties - .getProperty(ActiveStandbyProperties.NODE_NAME); - - logger.debug("testComputeMostRecentPrimary: Creating emfDrools"); - EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( - "junitDroolsPU", activeStandbyProperties); - - final DroolsPdpsConnector droolsPdpsConnector = new JpaDroolsPdpsConnector(emfDrools); - - - // Create 4 pdpd all not designated - - - long designatedDateMs = new Date().getTime(); - DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, new Date()); - pdp1.setDesignatedDate(new Date(designatedDateMs - 2)); - - DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, new Date()); - //oldest - pdp2.setDesignatedDate(new Date(designatedDateMs - 3)); - - DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, new Date()); - pdp3.setDesignatedDate(new Date(designatedDateMs - 1)); - - DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, new Date()); - //most recent - pdp4.setDesignatedDate(new Date(designatedDateMs)); - - ArrayList listOfAllPdps = new ArrayList(); - listOfAllPdps.add(pdp1); - listOfAllPdps.add(pdp2); - listOfAllPdps.add(pdp3); - listOfAllPdps.add(pdp4); - - - ArrayList listOfDesignated = new ArrayList(); - listOfDesignated.add(pdp1); - listOfDesignated.add(pdp2); - listOfDesignated.add(pdp3); - listOfDesignated.add(pdp4); - - // Because the way we sanitize the listOfDesignated, it will always contain all hot standby - // or all designated members. - - // Now we want to create a StateManagementFeature and initialize it. It will be - // discovered by the ActiveStandbyFeature when the election handler initializes. - - StateManagementFeatureApi stateManagementFeature = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - stateManagementFeature = feature; - logger.debug("testComputeMostRecentPrimary stateManagementFeature.getResourceName(): {}", - stateManagementFeature.getResourceName()); - break; - } - if (stateManagementFeature == null) { - logger.error("testComputeMostRecentPrimary failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testComputeMostRecentPrimary failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } - - DroolsPdpsElectionHandler droolsPdpsElectionHandler = new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1); - - DroolsPdp mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary( - listOfAllPdps, listOfDesignated); - - logger.debug("\n\ntestComputeMostRecentPrimary: mostRecentPrimary.getPdpId() = {}\n\n", - mostRecentPrimary.getPdpId()); - - - // If all of the pdps are included in the listOfDesignated and none are designated, it will choose - // the one which has the most recent designated date. - - - assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); - - - // Now let's designate all of those on the listOfDesignated. It will choose the first one designated - - - pdp1.setDesignated(true); - pdp2.setDesignated(true); - pdp3.setDesignated(true); - pdp4.setDesignated(true); - - mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); - - logger.debug("\n\ntestComputeMostRecentPrimary: All designated all on list, " - + "mostRecentPrimary.getPdpId() = {}\n\n", - mostRecentPrimary.getPdpId()); - - - // If all of the pdps are included in the listOfDesignated and all are designated, it will choose - // the one which was designated first - - - assertTrue(mostRecentPrimary.getPdpId().equals("pdp2")); - - - // Now we will designate only 2 and put just them in the listOfDesignated. The algorithm will now - // look for the most recently designated pdp which is not currently designated. - - - pdp3.setDesignated(false); - pdp4.setDesignated(false); - - listOfDesignated.remove(pdp3); - listOfDesignated.remove(pdp4); - - mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); - - logger.debug("\n\ntestComputeMostRecentPrimary: mostRecentPrimary.getPdpId() = {}\n\n", - mostRecentPrimary.getPdpId()); - - assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); - - - - // Now we will have none designated and put two of them in the listOfDesignated. The algorithm will now - // look for the most recently designated pdp regardless of whether it is currently marked as designated. - - - pdp1.setDesignated(false); - pdp2.setDesignated(false); - - mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); - - logger.debug("\n\ntestComputeMostRecentPrimary: 2 on list mostRecentPrimary.getPdpId() = {}\n\n", - mostRecentPrimary.getPdpId()); - - assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); - - - // If we have only one pdp on in the listOfDesignated, - // the most recently designated pdp will be chosen, regardless - // of its designation status - - - listOfDesignated.remove(pdp1); - - mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); - - logger.debug("\n\ntestComputeMostRecentPrimary: 1 on list mostRecentPrimary.getPdpId() = {}\n\n", - mostRecentPrimary.getPdpId()); - - assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); - - - // Finally, if none are on the listOfDesignated, it will again choose the most recently designated pdp. - - - listOfDesignated.remove(pdp2); - - mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); - - logger.debug("\n\ntestComputeMostRecentPrimary: 0 on list mostRecentPrimary.getPdpId() = {}\n\n", - mostRecentPrimary.getPdpId()); - - assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); - - } - - /** - * Test compute designated PDP. - * - * @throws Exception exception - */ - //@Ignore - //@Test - public void testComputeDesignatedPdp() throws Exception { - - logger.debug("\n\ntestComputeDesignatedPdp: Entering\n\n"); - - logger.debug("testComputeDesignatedPdp: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - String thisPdpId = activeStandbyProperties - .getProperty(ActiveStandbyProperties.NODE_NAME); - - - logger.debug("testComputeDesignatedPdp: Creating emfDrools"); - EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( - "junitDroolsPU", activeStandbyProperties); - - final DroolsPdpsConnector droolsPdpsConnector = new JpaDroolsPdpsConnector(emfDrools); - - - // Create 4 pdpd all not designated. Two on site1. Two on site2 - - - long designatedDateMs = new Date().getTime(); - DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, new Date()); - pdp1.setDesignatedDate(new Date(designatedDateMs - 2)); - pdp1.setSite("site1"); - - DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, new Date()); - pdp2.setDesignatedDate(new Date(designatedDateMs - 3)); - pdp2.setSite("site1"); - - //oldest - DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, new Date()); - pdp3.setDesignatedDate(new Date(designatedDateMs - 4)); - pdp3.setSite("site2"); - - DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, new Date()); - //most recent - pdp4.setDesignatedDate(new Date(designatedDateMs)); - pdp4.setSite("site2"); - - ArrayList listOfAllPdps = new ArrayList(); - listOfAllPdps.add(pdp1); - listOfAllPdps.add(pdp2); - listOfAllPdps.add(pdp3); - listOfAllPdps.add(pdp4); - - - ArrayList listOfDesignated = new ArrayList(); - - - // We will first test an empty listOfDesignated. As we know from the previous JUnit, - // the pdp with the most designated date will be chosen for mostRecentPrimary - - // Now we want to create a StateManagementFeature and initialize it. It will be - // discovered by the ActiveStandbyFeature when the election handler initializes. - - StateManagementFeatureApi stateManagementFeature = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - stateManagementFeature = feature; - logger.debug("testComputeDesignatedPdp stateManagementFeature.getResourceName(): {}", - stateManagementFeature.getResourceName()); - break; - } - if (stateManagementFeature == null) { - logger.error("testComputeDesignatedPdp failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testComputeDesignatedPdp failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } - - - DroolsPdpsElectionHandler droolsPdpsElectionHandler = new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1); - - DroolsPdp mostRecentPrimary = pdp4; - - DroolsPdp designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary); - - - // The designatedPdp should be null - - assertTrue(designatedPdp == null); - - - // Now let's try having only one pdp in listOfDesignated, but not in the same site as the most recent primary - - listOfDesignated.add(pdp2); - - designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary); - - - // Now the designatedPdp should be the one and only selection in the listOfDesignated - - - assertTrue(designatedPdp.getPdpId().equals(pdp2.getPdpId())); - - - // Now let's put 2 pdps in the listOfDesignated, neither in the same site as the mostRecentPrimary - - - listOfDesignated.add(pdp1); - - designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary); - - - // The designatedPdp should now be the one with the lowest lexiographic score - pdp1 - - - assertTrue(designatedPdp.getPdpId().equals(pdp1.getPdpId())); - - - // Finally, we will have 2 pdps in the listOfDesignated, one in the same site with the mostRecentPrimary - - - listOfDesignated.remove(pdp1); - listOfDesignated.add(pdp3); - - designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary); - - - // The designatedPdp should now be the one on the same site as the mostRecentPrimary - - - assertTrue(designatedPdp.getPdpId().equals(pdp3.getPdpId())); - } - - /** - * Test cold standby. - * - * @throws Exception exception - */ - //@Ignore - //@Test - public void testColdStandby() throws Exception { - - logger.debug("\n\ntestColdStandby: Entering\n\n"); - cleanXacmlDb(); - cleanDroolsDb(); - - logger.debug("testColdStandby: Reading stateManagementProperties"); - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); - - logger.debug("testColdStandby: Creating emfXacml"); - final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( - "junitXacmlPU", stateManagementProperties); - - logger.debug("testColdStandby: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - final String thisPdpId = activeStandbyProperties.getProperty(ActiveStandbyProperties.NODE_NAME); - - logger.debug("testColdStandby: Creating emfDrools"); - EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( - "junitDroolsPU", activeStandbyProperties); - - DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); - - logger.debug("testColdStandby: Cleaning up tables"); - conn.deleteAllPdps(); - - logger.debug("testColdStandby: Inserting PDP={} as designated", thisPdpId); - DroolsPdp pdp = new DroolsPdpImpl(thisPdpId, true, 4, new Date()); - conn.insertPdp(pdp); - DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); - logger.debug("testColdStandby: After insertion, DESIGNATED= {} " - + "for PDP= {}", droolsPdpEntity.isDesignated(), thisPdpId); - assertTrue(droolsPdpEntity.isDesignated() == true); - - /* - * When the Standby Status changes (from providingservice) to hotstandby - * or coldstandby,the Active/Standby selection algorithm must stand down - * if thePDP-D is currently the lead/active node and allow another PDP-D - * to take over. - * - * It must also call lock on all engines in the engine management. - */ - - - /* - * Yes, this is kludgy, but we have a chicken and egg problem here: we - * need a StateManagement object to invoke the - * deleteAllStateManagementEntities method. - */ - logger.debug("testColdStandby: Instantiating stateManagement object"); - - StateManagement sm = new StateManagement(emfXacml, "dummy"); - sm.deleteAllStateManagementEntities(); - - // Now we want to create a StateManagementFeature and initialize it. It will be - // discovered by the ActiveStandbyFeature when the election handler initializes. - - StateManagementFeatureApi smf = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - smf = feature; - logger.debug("testColdStandby stateManagementFeature.getResourceName(): {}", smf.getResourceName()); - break; - } - if (smf == null) { - logger.error("testColdStandby failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testColdStandby failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } - - // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature - // that has been created. - ActiveStandbyFeatureApi activeStandbyFeature = null; - for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - activeStandbyFeature = feature; - logger.debug("testColdStandby activeStandbyFeature.getResourceName(): {}", - activeStandbyFeature.getResourceName()); - break; - } - if (activeStandbyFeature == null) { - logger.error("testColdStandby failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID:{}", thisPdpId); - logger.debug("testColdStandby failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID:{}", thisPdpId); - } - - // Artificially putting a PDP into service is really a two step process, 1) - // inserting it as designated and 2) promoting it so that its standbyStatus - // is providing service. - - logger.debug("testColdStandby: Runner started; Sleeping " - + interruptRecoveryTime + "ms before promoting PDP= {}", - thisPdpId); - sleep(interruptRecoveryTime); - - logger.debug("testColdStandby: Promoting PDP={}", thisPdpId); - smf.promote(); - - String standbyStatus = sm.getStandbyStatus(thisPdpId); - logger.debug("testColdStandby: Before locking, PDP= {} has standbyStatus= {}", - thisPdpId, standbyStatus); - - logger.debug("testColdStandby: Locking smf"); - smf.lock(); - - sleep(interruptRecoveryTime); - - // Verify that the PDP is no longer designated. - - droolsPdpEntity = conn.getPdp(thisPdpId); - logger.debug("testColdStandby: After lock sm.lock() invoked, " - + "DESIGNATED= {} for PDP={}", droolsPdpEntity.isDesignated(), thisPdpId); - assertTrue(droolsPdpEntity.isDesignated() == false); - - logger.debug("\n\ntestColdStandby: Exiting\n\n"); - sleep(interruptRecoveryTime); - - } - - // Tests hot standby when there is only one PDP. - - /** - * Test hot standby 1. - * - * @throws Exception exception - */ - //@Ignore - //@Test - public void testHotStandby1() throws Exception { - - logger.debug("\n\ntestHotStandby1: Entering\n\n"); - cleanXacmlDb(); - cleanDroolsDb(); - - logger.debug("testHotStandby1: Reading stateManagementProperties"); - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); - - logger.debug("testHotStandby1: Creating emfXacml"); - final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( - "junitXacmlPU", stateManagementProperties); - - logger.debug("testHotStandby1: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - final String thisPdpId = activeStandbyProperties - .getProperty(ActiveStandbyProperties.NODE_NAME); - - logger.debug("testHotStandby1: Creating emfDrools"); - EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( - "junitDroolsPU", activeStandbyProperties); - - DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); - - logger.debug("testHotStandby1: Cleaning up tables"); - conn.deleteAllPdps(); - - /* - * Insert this PDP as not designated. Initial standby state will be - * either null or cold standby. Demoting should transit state to - * hot standby. - */ - - logger.debug("testHotStandby1: Inserting PDP={} as not designated", thisPdpId); - Date yesterday = DateUtils.addDays(new Date(), -1); - DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday); - conn.insertPdp(pdp); - DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); - logger.debug("testHotStandby1: After insertion, PDP={} has DESIGNATED={}", - thisPdpId, droolsPdpEntity.isDesignated()); - assertTrue(droolsPdpEntity.isDesignated() == false); - - logger.debug("testHotStandby1: Instantiating stateManagement object"); - StateManagement sm = new StateManagement(emfXacml, "dummy"); - sm.deleteAllStateManagementEntities(); - - - // Now we want to create a StateManagementFeature and initialize it. It will be - // discovered by the ActiveStandbyFeature when the election handler initializes. - - StateManagementFeatureApi smf = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - smf = feature; - logger.debug("testHotStandby1 stateManagementFeature.getResourceName(): {}", smf.getResourceName()); - break; - } - if (smf == null) { - logger.error("testHotStandby1 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testHotStandby1 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } - - // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature - // that has been created. - ActiveStandbyFeatureApi activeStandbyFeature = null; - for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - activeStandbyFeature = feature; - logger.debug("testHotStandby1 activeStandbyFeature.getResourceName(): {}", - activeStandbyFeature.getResourceName()); - break; - } - if (activeStandbyFeature == null) { - logger.error("testHotStandby1 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - logger.debug("testHotStandby1 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - } - - - logger.debug("testHotStandby1: Demoting PDP={}", thisPdpId); - // demoting should cause state to transit to hotstandby - smf.demote(); - - - logger.debug("testHotStandby1: Sleeping {} ms, to allow JpaDroolsPdpsConnector " - + "time to check droolspdpentity table", sleepTime); - sleep(sleepTime); - - - // Verify that this formerly un-designated PDP in HOT_STANDBY is now designated and providing service. - - droolsPdpEntity = conn.getPdp(thisPdpId); - logger.debug("testHotStandby1: After sm.demote() invoked, DESIGNATED= {} " - + "for PDP= {}", droolsPdpEntity.isDesignated(), thisPdpId); - assertTrue(droolsPdpEntity.isDesignated() == true); - String standbyStatus = smf.getStandbyStatus(thisPdpId); - logger.debug("testHotStandby1: After demotion, PDP= {} " - + "has standbyStatus= {}", thisPdpId, standbyStatus); - assertTrue(standbyStatus != null && standbyStatus.equals(StateManagement.PROVIDING_SERVICE)); - - logger.debug("testHotStandby1: Stopping policyManagementRunner"); - - logger.debug("\n\ntestHotStandby1: Exiting\n\n"); - sleep(interruptRecoveryTime); - - } - - /* - * Tests hot standby when two PDPs are involved. - */ - - /** - * Test hot standby 2. - * - * @throws Exception exception - */ - //@Ignore - //@Test - public void testHotStandby2() throws Exception { - - logger.info("\n\ntestHotStandby2: Entering\n\n"); - cleanXacmlDb(); - cleanDroolsDb(); - - logger.info("testHotStandby2: Reading stateManagementProperties"); - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); - - logger.info("testHotStandby2: Creating emfXacml"); - final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( - "junitXacmlPU", stateManagementProperties); - - logger.info("testHotStandby2: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - final String thisPdpId = activeStandbyProperties - .getProperty(ActiveStandbyProperties.NODE_NAME); - - logger.info("testHotStandby2: Creating emfDrools"); - EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( - "junitDroolsPU", activeStandbyProperties); - - DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); - - logger.info("testHotStandby2: Cleaning up tables"); - conn.deleteAllPdps(); - - - // Insert a PDP that's designated but not current. - - String activePdpId = "pdp2"; - logger.info("testHotStandby2: Inserting PDP={} as stale, designated PDP", activePdpId); - Date yesterday = DateUtils.addDays(new Date(), -1); - DroolsPdp pdp = new DroolsPdpImpl(activePdpId, true, 4, yesterday); - conn.insertPdp(pdp); - DroolsPdpEntity droolsPdpEntity = conn.getPdp(activePdpId); - logger.info("testHotStandby2: After insertion, PDP= {}, which is " - + "not current, has DESIGNATED= {}", activePdpId, droolsPdpEntity.isDesignated()); - assertTrue(droolsPdpEntity.isDesignated() == true); - - /* - * Promote the designated PDP. - * - * We have a chicken and egg problem here: we need a StateManagement - * object to invoke the deleteAllStateManagementEntities method. - */ - - - logger.info("testHotStandby2: Promoting PDP={}", activePdpId); - StateManagement sm = new StateManagement(emfXacml, "dummy"); - sm.deleteAllStateManagementEntities(); - - - sm = new StateManagement(emfXacml, activePdpId);//pdp2 - - // Artificially putting a PDP into service is really a two step process, 1) - // inserting it as designated and 2) promoting it so that its standbyStatus - // is providing service. - - /* - * Insert this PDP as not designated. Initial standby state will be - * either null or cold standby. Demoting should transit state to - * hot standby. - */ - - - logger.info("testHotStandby2: Inserting PDP= {} as not designated", thisPdpId); - pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday); - conn.insertPdp(pdp); - droolsPdpEntity = conn.getPdp(thisPdpId); - logger.info("testHotStandby2: After insertion, PDP={} " - + "has DESIGNATED= {}", thisPdpId, droolsPdpEntity.isDesignated()); - assertTrue(droolsPdpEntity.isDesignated() == false); - - - // Now we want to create a StateManagementFeature and initialize it. It will be - // discovered by the ActiveStandbyFeature when the election handler initializes. - - StateManagementFeatureApi sm2 = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - sm2 = feature; - logger.debug("testHotStandby2 stateManagementFeature.getResourceName(): {}", sm2.getResourceName()); - break; - } - if (sm2 == null) { - logger.error("testHotStandby2 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testHotStandby2 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } - - // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature - // that has been created. - ActiveStandbyFeatureApi activeStandbyFeature = null; - for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - activeStandbyFeature = feature; - logger.debug("testHotStandby2 activeStandbyFeature.getResourceName(): {}", - activeStandbyFeature.getResourceName()); - break; - } - if (activeStandbyFeature == null) { - logger.error("testHotStandby2 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - logger.debug("testHotStandby2 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - } - - logger.info("testHotStandby2: Runner started; Sleeping {} " - + "ms before promoting/demoting", interruptRecoveryTime); - sleep(interruptRecoveryTime); - - logger.info("testHotStandby2: Runner started; promoting PDP={}", activePdpId); - //At this point, the newly created pdp will have set the state to disabled/failed/cold standby - //because it is stale. So, it cannot be promoted. We need to call sm.enableNotFailed() so we - //can promote it and demote the other pdp - else the other pdp will just spring back to providingservice - sm.enableNotFailed();//pdp2 - sm.promote(); - String standbyStatus = sm.getStandbyStatus(activePdpId); - logger.info("testHotStandby2: After promoting, PDP= {} has standbyStatus= {}", activePdpId, standbyStatus); - - // demoting PDP should ensure that state transits to hotstandby - logger.info("testHotStandby2: Runner started; demoting PDP= {}", thisPdpId); - sm2.demote();//pdp1 - standbyStatus = sm.getStandbyStatus(thisPdpId); - logger.info("testHotStandby2: After demoting, PDP={} has standbyStatus= {}",thisPdpId , standbyStatus); - - logger.info("testHotStandby2: Sleeping {} ms, to allow JpaDroolsPdpsConnector " - + "time to check droolspdpentity table", sleepTime); - sleep(sleepTime); - - /* - * Verify that this PDP, demoted to HOT_STANDBY, is now - * re-designated and providing service. - */ - - droolsPdpEntity = conn.getPdp(thisPdpId); - logger.info("testHotStandby2: After demoting PDP={}" - + ", DESIGNATED= {}" - + " for PDP= {}", activePdpId, droolsPdpEntity.isDesignated(), thisPdpId); - assertTrue(droolsPdpEntity.isDesignated() == true); - standbyStatus = sm2.getStandbyStatus(thisPdpId); - logger.info("testHotStandby2: After demoting PDP={}" - + ", PDP={} has standbyStatus= {}", - activePdpId, thisPdpId, standbyStatus); - assertTrue(standbyStatus != null - && standbyStatus.equals(StateManagement.PROVIDING_SERVICE)); - - logger.info("testHotStandby2: Stopping policyManagementRunner"); - - logger.info("\n\ntestHotStandby2: Exiting\n\n"); - sleep(interruptRecoveryTime); - - } - - /* - * 1) Inserts and designates this PDP, then verifies that startTransaction - * is successful. - * - * 2) Demotes PDP, and verifies that because there is only one PDP, it will - * be immediately re-promoted, thus allowing startTransaction to be - * successful. - * - * 3) Locks PDP and verifies that startTransaction results in - * AdministrativeStateException. - * - * 4) Unlocks PDP and verifies that startTransaction results in - * StandbyStatusException. - * - * 5) Promotes PDP and verifies that startTransaction is once again - * successful. - */ - - /** - * Test locking. - * - * @throws Exception exception - */ - //@Ignore - //@Test - public void testLocking1() throws Exception { - logger.debug("testLocking1: Entry"); - cleanXacmlDb(); - cleanDroolsDb(); - - logger.debug("testLocking1: Reading stateManagementProperties"); - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); - - logger.debug("testLocking1: Creating emfXacml"); - final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( - "junitXacmlPU", stateManagementProperties); - - logger.debug("testLocking1: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - final String thisPdpId = activeStandbyProperties - .getProperty(ActiveStandbyProperties.NODE_NAME); - - logger.debug("testLocking1: Creating emfDrools"); - EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( - "junitDroolsPU", activeStandbyProperties); - - DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); - - logger.debug("testLocking1: Cleaning up tables"); - conn.deleteAllPdps(); - - /* - * Insert this PDP as designated. Initial standby state will be - * either null or cold standby. - */ - - logger.debug("testLocking1: Inserting PDP= {} as designated", thisPdpId); - DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, true, 4, new Date()); - conn.insertPdp(pdp); - DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); - logger.debug("testLocking1: After insertion, PDP= {} has DESIGNATED= {}", - thisPdpId, droolsPdpEntity.isDesignated()); - assertTrue(droolsPdpEntity.isDesignated() == true); - - logger.debug("testLocking1: Instantiating stateManagement object"); - StateManagement smDummy = new StateManagement(emfXacml, "dummy"); - smDummy.deleteAllStateManagementEntities(); - - // Now we want to create a StateManagementFeature and initialize it. It will be - // discovered by the ActiveStandbyFeature when the election handler initializes. - - StateManagementFeatureApi sm = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - sm = feature; - logger.debug("testLocking1 stateManagementFeature.getResourceName(): {}", sm.getResourceName()); - break; - } - if (sm == null) { - logger.error("testLocking1 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testLocking1 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } - - // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature - // that has been created. - ActiveStandbyFeatureApi activeStandbyFeature = null; - for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - activeStandbyFeature = feature; - logger.debug("testLocking1 activeStandbyFeature.getResourceName(): {}", - activeStandbyFeature.getResourceName()); - break; - } - if (activeStandbyFeature == null) { - logger.error("testLocking1 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - logger.debug("testLocking1 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - } - - logger.debug("testLocking1: Runner started; Sleeping " - + interruptRecoveryTime + "ms before promoting PDP={}", - thisPdpId); - sleep(interruptRecoveryTime); - - logger.debug("testLocking1: Promoting PDP={}", thisPdpId); - sm.promote(); - - logger.debug("testLocking1: Sleeping {} ms, to allow time for " - + "policy-management.Main class to come up, designated= {}", - sleepTime, conn.getPdp(thisPdpId).isDesignated()); - sleep(sleepTime); - - logger.debug("testLocking1: Waking up and invoking startTransaction on active PDP={}" - + ", designated= {}",thisPdpId, conn.getPdp(thisPdpId).isDesignated()); - - - IntegrityMonitor droolsPdpIntegrityMonitor = IntegrityMonitor.getInstance(); - try { - droolsPdpIntegrityMonitor.startTransaction(); - droolsPdpIntegrityMonitor.endTransaction(); - logger.debug("testLocking1: As expected, transaction successful"); - } catch (AdministrativeStateException e) { - logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, ", e); - assertTrue(false); - } catch (StandbyStatusException e) { - logger.error("testLocking1: Unexpectedly caught StandbyStatusException, ", e); - assertTrue(false); - } catch (Exception e) { - logger.error("testLocking1: Unexpectedly caught Exception, ", e); - assertTrue(false); - } - - // demoting should cause state to transit to hotstandby, followed by re-promotion, - // since there is only one PDP. - logger.debug("testLocking1: demoting PDP={}", thisPdpId); - sm.demote(); - - logger.debug("testLocking1: sleeping" + electionWaitSleepTime - + " to allow election handler to re-promote PDP={}", thisPdpId); - sleep(electionWaitSleepTime); - - logger.debug("testLocking1: Invoking startTransaction on re-promoted PDP={}" - + ", designated={}", thisPdpId, conn.getPdp(thisPdpId).isDesignated()); - try { - droolsPdpIntegrityMonitor.startTransaction(); - droolsPdpIntegrityMonitor.endTransaction(); - logger.debug("testLocking1: As expected, transaction successful"); - } catch (AdministrativeStateException e) { - logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, ", e); - assertTrue(false); - } catch (StandbyStatusException e) { - logger.error("testLocking1: Unexpectedly caught StandbyStatusException, ", e); - assertTrue(false); - } catch (Exception e) { - logger.error("testLocking1: Unexpectedly caught Exception, ", e); - assertTrue(false); - } - - // locking should cause state to transit to cold standby - logger.debug("testLocking1: locking PDP={}", thisPdpId); - sm.lock(); - - // Just to avoid any race conditions, sleep a little after locking - logger.debug("testLocking1: Sleeping a few millis after locking, to avoid race condition"); - sleep(100); - - logger.debug("testLocking1: Invoking startTransaction on locked PDP= {}" - + ", designated= {}",thisPdpId, conn.getPdp(thisPdpId).isDesignated()); - try { - droolsPdpIntegrityMonitor.startTransaction(); - logger.error("testLocking1: startTransaction unexpectedly successful"); - assertTrue(false); - } catch (AdministrativeStateException e) { - logger.debug("testLocking1: As expected, caught AdministrativeStateException, ", e); - } catch (StandbyStatusException e) { - logger.error("testLocking1: Unexpectedly caught StandbyStatusException, ", e); - assertTrue(false); - } catch (Exception e) { - logger.error("testLocking1: Unexpectedly caught Exception, ", e); - assertTrue(false); - } finally { - droolsPdpIntegrityMonitor.endTransaction(); - } - - // unlocking should cause state to transit to hot standby and then providing service - logger.debug("testLocking1: unlocking PDP={}", thisPdpId); - sm.unlock(); - - // Just to avoid any race conditions, sleep a little after locking - logger.debug("testLocking1: Sleeping a few millis after unlocking, to avoid race condition"); - sleep(electionWaitSleepTime); - - logger.debug("testLocking1: Invoking startTransaction on unlocked PDP=" - + thisPdpId - + ", designated=" - + conn.getPdp(thisPdpId).isDesignated()); - try { - droolsPdpIntegrityMonitor.startTransaction(); - logger.error("testLocking1: startTransaction successful as expected"); - } catch (AdministrativeStateException e) { - logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, ", e); - assertTrue(false); - } catch (StandbyStatusException e) { - logger.debug("testLocking1: Unexpectedly caught StandbyStatusException, ", e); - assertTrue(false); - } catch (Exception e) { - logger.error("testLocking1: Unexpectedly caught Exception, ", e); - assertTrue(false); - } finally { - droolsPdpIntegrityMonitor.endTransaction(); - } - - // demoting should cause state to transit to hot standby - logger.debug("testLocking1: demoting PDP={}", thisPdpId); - sm.demote(); - - // Just to avoid any race conditions, sleep a little after promoting - logger.debug("testLocking1: Sleeping a few millis after demoting, to avoid race condition"); - sleep(100); - - logger.debug("testLocking1: Invoking startTransaction on demoted PDP={}" - + ", designated={}", thisPdpId, conn.getPdp(thisPdpId).isDesignated()); - try { - droolsPdpIntegrityMonitor.startTransaction(); - droolsPdpIntegrityMonitor.endTransaction(); - logger.debug("testLocking1: Unexpectedly, transaction successful"); - assertTrue(false); - } catch (AdministrativeStateException e) { - logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, ", e); - assertTrue(false); - } catch (StandbyStatusException e) { - logger.error("testLocking1: As expected caught StandbyStatusException, ", e); - } catch (Exception e) { - logger.error("testLocking1: Unexpectedly caught Exception, ", e); - assertTrue(false); - } - - logger.debug("\n\ntestLocking1: Exiting\n\n"); - sleep(interruptRecoveryTime); - - } - - - /* - * 1) Inserts and designates this PDP, then verifies that startTransaction - * is successful. - * - * 2) Inserts another PDP in hotstandby. - * - * 3) Demotes this PDP, and verifies 1) that other PDP is not promoted (because one - * PDP cannot promote another PDP) and 2) that this PDP is re-promoted. - */ - - /** - * Test locking 2. - * - * @throws Exception exception - */ - //@Ignore - //@Test - public void testLocking2() throws Exception { - - logger.debug("\n\ntestLocking2: Entering\n\n"); - cleanXacmlDb(); - cleanDroolsDb(); - - logger.debug("testLocking2: Reading stateManagementProperties"); - Properties stateManagementProperties = new Properties(); - stateManagementProperties.load(new FileInputStream(new File( - configDir + "/feature-state-management.properties"))); - - logger.debug("testLocking2: Creating emfXacml"); - final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( - "junitXacmlPU", stateManagementProperties); - - logger.debug("testLocking2: Reading activeStandbyProperties"); - Properties activeStandbyProperties = new Properties(); - activeStandbyProperties.load(new FileInputStream(new File( - configDir + "/feature-active-standby-management.properties"))); - final String thisPdpId = activeStandbyProperties - .getProperty(ActiveStandbyProperties.NODE_NAME); - - logger.debug("testLocking2: Creating emfDrools"); - EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( - "junitDroolsPU", activeStandbyProperties); - - DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); - - logger.debug("testLocking2: Cleaning up tables"); - conn.deleteAllPdps(); - - /* - * Insert this PDP as designated. Initial standby state will be - * either null or cold standby. Demoting should transit state to - * hot standby. - */ - - logger.debug("testLocking2: Inserting PDP= {} as designated", thisPdpId); - DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, true, 3, new Date()); - conn.insertPdp(pdp); - DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); - logger.debug("testLocking2: After insertion, PDP= {} has DESIGNATED= {}", - thisPdpId, droolsPdpEntity.isDesignated()); - assertTrue(droolsPdpEntity.isDesignated() == true); - - logger.debug("testLocking2: Instantiating stateManagement object and promoting PDP={}", thisPdpId); - StateManagement smDummy = new StateManagement(emfXacml, "dummy"); - smDummy.deleteAllStateManagementEntities(); - - // Now we want to create a StateManagementFeature and initialize it. It will be - // discovered by the ActiveStandbyFeature when the election handler initializes. - - StateManagementFeatureApi sm = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - sm = feature; - logger.debug("testLocking2 stateManagementFeature.getResourceName(): {}", sm.getResourceName()); - break; - } - if (sm == null) { - logger.error("testLocking2 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - logger.debug("testLocking2 failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", thisPdpId); - } - - // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature - // that has been created. - ActiveStandbyFeatureApi activeStandbyFeature = null; - for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { - ((PolicySessionFeatureApi) feature).globalInit(null, configDir); - activeStandbyFeature = feature; - logger.debug("testLocking2 activeStandbyFeature.getResourceName(): {}", - activeStandbyFeature.getResourceName()); - break; - } - if (activeStandbyFeature == null) { - logger.error("testLocking2 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - logger.debug("testLocking2 failed to initialize. " - + "Unable to get instance of ActiveStandbyFeatureAPI " - + "with resourceID: {}", thisPdpId); - } - - /* - * Insert another PDP as not designated. Initial standby state will be - * either null or cold standby. Demoting should transit state to - * hot standby. - */ - - String standbyPdpId = "pdp2"; - logger.debug("testLocking2: Inserting PDP= {} as not designated", standbyPdpId); - Date yesterday = DateUtils.addDays(new Date(), -1); - pdp = new DroolsPdpImpl(standbyPdpId, false, 4, yesterday); - conn.insertPdp(pdp); - droolsPdpEntity = conn.getPdp(standbyPdpId); - logger.debug("testLocking2: After insertion, PDP={} has DESIGNATED= {}", - standbyPdpId, droolsPdpEntity.isDesignated()); - assertTrue(droolsPdpEntity.isDesignated() == false); - - logger.debug("testLocking2: Demoting PDP= {}", standbyPdpId); - final StateManagement sm2 = new StateManagement(emfXacml, standbyPdpId); - - logger.debug("testLocking2: Runner started; Sleeping {} ms " - + "before promoting/demoting", interruptRecoveryTime); - sleep(interruptRecoveryTime); - - logger.debug("testLocking2: Promoting PDP= {}", thisPdpId); - sm.promote(); - - // demoting PDP should ensure that state transits to hotstandby - logger.debug("testLocking2: Demoting PDP={}", standbyPdpId); - sm2.demote(); - - logger.debug("testLocking2: Sleeping {} ms, to allow time for to come up", sleepTime); - sleep(sleepTime); - - logger.debug("testLocking2: Waking up and invoking startTransaction on active PDP={}" - + ", designated= {}", thisPdpId, conn.getPdp(thisPdpId).isDesignated()); - - IntegrityMonitor droolsPdpIntegrityMonitor = IntegrityMonitor.getInstance(); - - try { - droolsPdpIntegrityMonitor.startTransaction(); - droolsPdpIntegrityMonitor.endTransaction(); - logger.debug("testLocking2: As expected, transaction successful"); - } catch (AdministrativeStateException e) { - logger.error("testLocking2: Unexpectedly caught AdministrativeStateException, ", e); - assertTrue(false); - } catch (StandbyStatusException e) { - logger.error("testLocking2: Unexpectedly caught StandbyStatusException, ", e); - assertTrue(false); - } catch (Exception e) { - logger.error("testLocking2: Unexpectedly caught Exception, ", e); - assertTrue(false); - } - - // demoting should cause state to transit to hotstandby followed by re-promotion. - logger.debug("testLocking2: demoting PDP={}", thisPdpId); - sm.demote(); - - logger.debug("testLocking2: sleeping {}" - + " to allow election handler to re-promote PDP={}", electionWaitSleepTime, thisPdpId); - sleep(electionWaitSleepTime); - - logger.debug("testLocking2: Waking up and invoking startTransaction " - + "on re-promoted PDP= {}, designated= {}", - thisPdpId, conn.getPdp(thisPdpId).isDesignated()); - try { - droolsPdpIntegrityMonitor.startTransaction(); - droolsPdpIntegrityMonitor.endTransaction(); - logger.debug("testLocking2: As expected, transaction successful"); - } catch (AdministrativeStateException e) { - logger.error("testLocking2: Unexpectedly caught AdministrativeStateException, ", e); - assertTrue(false); - } catch (StandbyStatusException e) { - logger.error("testLocking2: Unexpectedly caught StandbyStatusException, ", e); - assertTrue(false); - } catch (Exception e) { - logger.error("testLocking2: Unexpectedly caught Exception, ", e); - assertTrue(false); - } - - logger.debug("testLocking2: Verifying designated status for PDP= {}", standbyPdpId); - boolean standbyPdpDesignated = conn.getPdp(standbyPdpId).isDesignated(); - assertTrue(standbyPdpDesignated == false); - - logger.debug("\n\ntestLocking2: Exiting\n\n"); - sleep(interruptRecoveryTime); - } - - private void sleep(long sleepms) throws InterruptedException { - Thread.sleep(sleepms); - } -} diff --git a/feature-active-standby-management/src/test/resources/META-INF/persistence.xml b/feature-active-standby-management/src/test/resources/META-INF/persistence.xml index 549f01de..ecbf22b7 100644 --- a/feature-active-standby-management/src/test/resources/META-INF/persistence.xml +++ b/feature-active-standby-management/src/test/resources/META-INF/persistence.xml @@ -31,15 +31,6 @@ - - - - - - diff --git a/feature-active-standby-management/src/test/resources/asw/feature-active-standby-management.properties b/feature-active-standby-management/src/test/resources/asw/feature-active-standby-management.properties index f0711e6c..9b01736c 100644 --- a/feature-active-standby-management/src/test/resources/asw/feature-active-standby-management.properties +++ b/feature-active-standby-management/src/test/resources/asw/feature-active-standby-management.properties @@ -20,7 +20,7 @@ # DB properties javax.persistence.jdbc.driver = org.h2.Driver -javax.persistence.jdbc.url = jdbc:h2:file:./sql/activestandbymanagement +javax.persistence.jdbc.url = jdbc:h2:mem:asw_activestandbymanagement javax.persistence.jdbc.user = sa javax.persistence.jdbc.password = diff --git a/feature-active-standby-management/src/test/resources/asw/feature-state-management.properties b/feature-active-standby-management/src/test/resources/asw/feature-state-management.properties index 2629c63d..a5403c9f 100644 --- a/feature-active-standby-management/src/test/resources/asw/feature-state-management.properties +++ b/feature-active-standby-management/src/test/resources/asw/feature-state-management.properties @@ -20,7 +20,7 @@ # DB properties javax.persistence.jdbc.driver = org.h2.Driver -javax.persistence.jdbc.url = jdbc:h2:file:./sql/statemanagement +javax.persistence.jdbc.url = jdbc:h2:mem:asw_statemanagement javax.persistence.jdbc.user = sa javax.persistence.jdbc.password = @@ -28,7 +28,7 @@ javax.persistence.jdbc.password = http.server.services=TEST http.server.services.TEST.host=0.0.0.0 -http.server.services.TEST.port=9981 +http.server.services.TEST.port=9982 #These properties will default to the following if no other values are provided: # http.server.services.TEST.restClasses=org.onap.policy.drools.statemanagement.IntegrityMonitorRestManager # http.server.services.TEST.managed=false diff --git a/feature-active-standby-management/src/test/resources/feature-active-standby-management.properties b/feature-active-standby-management/src/test/resources/feature-active-standby-management.properties index 827d2e17..9e481b59 100644 --- a/feature-active-standby-management/src/test/resources/feature-active-standby-management.properties +++ b/feature-active-standby-management/src/test/resources/feature-active-standby-management.properties @@ -20,7 +20,7 @@ # DB properties javax.persistence.jdbc.driver = org.h2.Driver -javax.persistence.jdbc.url = jdbc:h2:file:./sql/activestandbymanagement +javax.persistence.jdbc.url = jdbc:h2:mem:activestandbymanagement javax.persistence.jdbc.user = sa javax.persistence.jdbc.password = diff --git a/feature-active-standby-management/src/test/resources/feature-state-management.properties b/feature-active-standby-management/src/test/resources/feature-state-management.properties index 3dd88473..ec840901 100644 --- a/feature-active-standby-management/src/test/resources/feature-state-management.properties +++ b/feature-active-standby-management/src/test/resources/feature-state-management.properties @@ -20,7 +20,7 @@ # DB properties javax.persistence.jdbc.driver = org.h2.Driver -javax.persistence.jdbc.url = jdbc:h2:file:./sql/statemanagement +javax.persistence.jdbc.url = jdbc:h2:mem:statemanagement javax.persistence.jdbc.user = sa javax.persistence.jdbc.password = -- cgit 1.2.3-korg