2 * ============LICENSE_START=======================================================
3 * feature-active-standby-management
4 * ================================================================================
5 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.drools.activestandby;
23 import static org.junit.Assert.assertFalse;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26 import static org.mockito.Mockito.mock;
27 import static org.mockito.Mockito.when;
29 import java.io.FileInputStream;
30 import java.io.IOException;
31 import java.util.Date;
32 import java.util.Properties;
33 import java.util.concurrent.Callable;
34 import javax.persistence.EntityManager;
35 import javax.persistence.EntityManagerFactory;
36 import javax.persistence.EntityTransaction;
37 import javax.persistence.Persistence;
38 import org.apache.commons.lang3.time.DateUtils;
39 import org.junit.AfterClass;
40 import org.junit.Before;
41 import org.junit.BeforeClass;
42 import org.junit.Test;
43 import org.onap.policy.common.im.IntegrityMonitor;
44 import org.onap.policy.common.im.IntegrityMonitorException;
45 import org.onap.policy.common.im.MonitorTime;
46 import org.onap.policy.common.im.StateManagement;
47 import org.onap.policy.common.utils.time.CurrentTime;
48 import org.onap.policy.common.utils.time.PseudoTimer;
49 import org.onap.policy.common.utils.time.TestTimeMulti;
50 import org.onap.policy.drools.core.PolicySessionFeatureApi;
51 import org.onap.policy.drools.statemanagement.StateManagementFeatureApi;
52 import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants;
53 import org.powermock.reflect.Whitebox;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * Testing the allSeemsWell interface to verify that it correctly affects the
62 public class AllSeemsWellTest {
63 private static final Logger logger = LoggerFactory.getLogger(AllSeemsWellTest.class);
65 private static final String MONITOR_FIELD_NAME = "instance";
66 private static final String HANDLER_INSTANCE_FIELD = "electionHandler";
69 * Currently, the DroolsPdpsElectionHandler.DesignationWaiter is invoked every 1 seconds, starting
70 * at the start of the next multiple of pdpUpdateInterval, but with a minimum of 5 sec cushion
71 * to ensure that we wait for the DesignationWaiter to do its job, before
72 * checking the results. Add a few seconds for safety
75 private static final int SLEEP_TIME_SEC = 10;
78 * DroolsPdpsElectionHandler runs every 1 seconds, so it takes 10 seconds for the
79 * checkWaitTimer() method to time out and call allSeemsWell which then requires
80 * the forward progress counter to go stale which should add an additional 5 sec.
83 private static final int STALLED_ELECTION_HANDLER_SLEEP_TIME_SEC = 15;
86 * As soon as the election hander successfully runs, it will resume the forward progress.
87 * If the election handler runs ever 1 sec and test transaction is run every 1 sec and
88 * then fpc is written every 1 sec and then the fpc is checked every 2 sec, that could
89 * take a total of 5 sec to recognize the resumption of progress. So, add 1 for safety.
91 private static final int RESUMED_ELECTION_HANDLER_SLEEP_TIME_SEC = 6;
93 private static EntityManagerFactory emfx;
94 private static EntityManagerFactory emfd;
95 private static EntityManager emx;
96 private static EntityManager emd;
97 private static EntityTransaction et;
99 private static final String CONFIG_DIR = "src/test/resources/asw";
101 private static CurrentTime saveTime;
102 private static Factory saveFactory;
104 private TestTimeMulti testTime;
107 * See the IntegrityMonitor.getJmxUrl() method for the rationale behind this jmx related processing.
113 * @throws Exception exception
116 public static void setUpClass() throws Exception {
118 String userDir = System.getProperty("user.dir");
119 logger.debug("setUpClass: userDir={}", userDir);
120 System.setProperty("com.sun.management.jmxremote.port", "9980");
121 System.setProperty("com.sun.management.jmxremote.authenticate","false");
123 DroolsPdpsElectionHandler.setIsUnitTesting(true);
125 saveTime = Whitebox.getInternalState(MonitorTime.class, MONITOR_FIELD_NAME);
126 saveFactory = Factory.getInstance();
128 resetInstanceObjects();
130 //Create the data access for xacml db
131 Properties stateManagementProperties = loadStateManagementProperties();
133 emfx = Persistence.createEntityManagerFactory("junitXacmlPU", stateManagementProperties);
135 // Create an entity manager to use the DB
136 emx = emfx.createEntityManager();
138 //Create the data access for drools db
139 Properties activeStandbyProperties = loadActiveStandbyProperties();
141 emfd = Persistence.createEntityManagerFactory("junitDroolsPU", activeStandbyProperties);
143 // Create an entity manager to use the DB
144 emd = emfd.createEntityManager();
148 * Restores the system state.
150 * @throws IntegrityMonitorException if the integrity monitor cannot be shut down
153 public static void tearDownClass() throws IntegrityMonitorException {
154 resetInstanceObjects();
156 Whitebox.setInternalState(MonitorTime.class, MONITOR_FIELD_NAME, saveTime);
157 Factory.setInstance(saveFactory);
159 DroolsPdpsElectionHandler.setIsUnitTesting(false);
171 * @throws Exception exception
174 public void setUp() throws Exception {
175 resetInstanceObjects();
178 testTime = new TestTimeMulti();
179 Whitebox.setInternalState(MonitorTime.class, MONITOR_FIELD_NAME, testTime);
181 Factory factory = mock(Factory.class);
182 when(factory.makeTimer()).thenAnswer(ans -> new PseudoTimer(testTime));
183 Factory.setInstance(factory);
186 private static void resetInstanceObjects() throws IntegrityMonitorException {
187 IntegrityMonitor.setUnitTesting(true);
188 IntegrityMonitor.deleteInstance();
189 IntegrityMonitor.setUnitTesting(false);
191 Whitebox.setInternalState(ActiveStandbyFeature.class, HANDLER_INSTANCE_FIELD, (Object) null);
196 * Clean the xacml database.
198 public void cleanXacmlDb() {
199 et = emx.getTransaction();
202 // Make sure we leave the DB clean
203 emx.createQuery("DELETE FROM StateManagementEntity").executeUpdate();
204 emx.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate();
205 emx.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate();
211 * Clean the drools database.
213 public void cleanDroolsDb() {
214 et = emd.getTransaction();
217 // Make sure we leave the DB clean
218 emd.createQuery("DELETE FROM DroolsPdpEntity").executeUpdate();
224 // Tests hot standby when there is only one PDP.
228 public void testAllSeemsWell() throws Exception {
230 logger.debug("\n\ntestAllSeemsWell: Entering\n\n");
234 Properties stateManagementProperties = loadStateManagementProperties();
236 logger.debug("testAllSeemsWell: Creating emfXacml");
237 final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory(
238 "junitXacmlPU", stateManagementProperties);
240 Properties activeStandbyProperties = loadActiveStandbyProperties();
241 final String thisPdpId = activeStandbyProperties
242 .getProperty(ActiveStandbyProperties.NODE_NAME);
244 logger.debug("testAllSeemsWell: Creating emfDrools");
245 EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory(
246 "junitDroolsPU", activeStandbyProperties);
248 DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools);
250 logger.debug("testAllSeemsWell: Cleaning up tables");
251 conn.deleteAllPdps();
254 * Insert this PDP as not designated. Initial standby state will be
255 * either null or cold standby. Demoting should transit state to
259 logger.debug("testAllSeemsWell: Inserting PDP={} as not designated", thisPdpId);
260 Date yesterday = DateUtils.addDays(testTime.getDate(), -1);
261 DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday);
263 DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId);
264 logger.debug("testAllSeemsWell: After insertion, PDP={} has DESIGNATED={}",
265 thisPdpId, droolsPdpEntity.isDesignated());
266 assertFalse(droolsPdpEntity.isDesignated());
268 logger.debug("testAllSeemsWell: Instantiating stateManagement object");
269 StateManagement sm = new StateManagement(emfXacml, "dummy");
270 sm.deleteAllStateManagementEntities();
273 // Now we want to create a StateManagementFeature and initialize it. It will be
274 // discovered by the ActiveStandbyFeature when the election handler initializes.
276 StateManagementFeatureApi stateManagementFeatureApi = null;
277 for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) {
278 ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR);
279 stateManagementFeatureApi = feature;
280 logger.debug("testAllSeemsWell stateManagementFeature.getResourceName(): {}",
281 stateManagementFeatureApi.getResourceName());
284 assertNotNull(stateManagementFeatureApi);
286 final StateManagementFeatureApi smf = stateManagementFeatureApi;
288 // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature
289 // that has been created.
290 ActiveStandbyFeatureApi activeStandbyFeature = null;
291 for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) {
292 ((PolicySessionFeatureApi) feature).globalInit(null, CONFIG_DIR);
293 activeStandbyFeature = feature;
294 logger.debug("testAllSeemsWell activeStandbyFeature.getResourceName(): {}",
295 activeStandbyFeature.getResourceName());
298 assertNotNull(activeStandbyFeature);
301 logger.debug("testAllSeemsWell: Demoting PDP={}", thisPdpId);
302 // demoting should cause state to transit to hotstandby
306 logger.debug("testAllSeemsWell: Sleeping {} s, to allow JpaDroolsPdpsConnector "
307 + "time to check droolspdpentity table", SLEEP_TIME_SEC);
308 waitForCondition(() -> conn.getPdp(thisPdpId).isDesignated(), SLEEP_TIME_SEC);
310 // Verify that this formerly un-designated PDP in HOT_STANDBY is now designated and providing service.
312 droolsPdpEntity = conn.getPdp(thisPdpId);
313 logger.debug("testAllSeemsWell: After sm.demote() invoked, DESIGNATED= {} "
314 + "for PDP= {}", droolsPdpEntity.isDesignated(), thisPdpId);
315 assertTrue(droolsPdpEntity.isDesignated());
316 String standbyStatus = smf.getStandbyStatus(thisPdpId);
317 logger.debug("testAllSeemsWell: After demotion, PDP= {} "
318 + "has standbyStatus= {}", thisPdpId, standbyStatus);
319 assertTrue(standbyStatus != null && standbyStatus.equals(StateManagement.PROVIDING_SERVICE));
321 //Now we want to stall the election handler and see the if AllSeemsWell will make the
322 //standbystatus = coldstandby
324 DroolsPdpsElectionHandler.setIsStalled(true);
326 logger.debug("testAllSeemsWell: Sleeping {} s, to allow checkWaitTimer to recognize "
327 + "the election handler has stalled and for the testTransaction to fail to "
328 + "increment forward progress and for the lack of forward progress to be recognized.",
329 STALLED_ELECTION_HANDLER_SLEEP_TIME_SEC);
332 //It takes 10x the update interval (1 sec) before the watcher will declare the election handler dead
333 //and that just stops forward progress counter. So, the fp monitor must then run to determine
334 // if the fpc has stalled. That will take about another 5 sec.
335 waitForCondition(() -> smf.getStandbyStatus().equals(StateManagement.COLD_STANDBY),
336 STALLED_ELECTION_HANDLER_SLEEP_TIME_SEC);
338 logger.debug("testAllSeemsWell: After isStalled=true, PDP= {} "
339 + "has standbyStatus= {}", thisPdpId, smf.getStandbyStatus(thisPdpId));
341 assertTrue(smf.getStandbyStatus().equals(StateManagement.COLD_STANDBY));
343 //Now lets resume the election handler
344 DroolsPdpsElectionHandler.setIsStalled(false);
346 waitForCondition(() -> smf.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE),
347 RESUMED_ELECTION_HANDLER_SLEEP_TIME_SEC);
349 logger.debug("testAllSeemsWell: After isStalled=false, PDP= {} "
350 + "has standbyStatus= {}", thisPdpId, smf.getStandbyStatus(thisPdpId));
352 assertTrue(smf.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE));
354 //resumedElectionHandlerSleepTime = 5000;
355 logger.debug("\n\ntestAllSeemsWell: Exiting\n\n");
359 private static Properties loadStateManagementProperties() throws IOException {
360 try (FileInputStream input = new FileInputStream(CONFIG_DIR + "/feature-state-management.properties")) {
361 Properties props = new Properties();
367 private static Properties loadActiveStandbyProperties() throws IOException {
368 try (FileInputStream input =
369 new FileInputStream(CONFIG_DIR + "/feature-active-standby-management.properties")) {
370 Properties props = new Properties();
376 private void waitForCondition(Callable<Boolean> testCondition, int timeoutInSeconds) throws InterruptedException {
377 testTime.waitUntil(testCondition);