2616ac34b4e10f05d65a3fd230549948acd65108
[policy/drools-pdp.git] /
1 /*
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.drools.activestandby;
22
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;
28
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;
56
57 /*
58  * Testing the allSeemsWell interface to verify that it correctly affects the
59  * operational state.
60  */
61
62 public class AllSeemsWellTest {
63     private static final Logger  logger = LoggerFactory.getLogger(AllSeemsWellTest.class);
64
65     private static final String MONITOR_FIELD_NAME = "instance";
66     private static final String HANDLER_INSTANCE_FIELD = "electionHandler";
67
68     /*
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
73      */
74
75     private static final int SLEEP_TIME_SEC = 10;
76
77     /*
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.
81      */
82
83     private static final int STALLED_ELECTION_HANDLER_SLEEP_TIME_SEC = 15;
84
85     /*
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.
90      */
91     private static final int RESUMED_ELECTION_HANDLER_SLEEP_TIME_SEC = 6;
92
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;
98
99     private static final String CONFIG_DIR = "src/test/resources/asw";
100
101     private static CurrentTime saveTime;
102     private static Factory saveFactory;
103
104     private TestTimeMulti testTime;
105
106     /*
107      * See the IntegrityMonitor.getJmxUrl() method for the rationale behind this jmx related processing.
108      */
109
110     /**
111      * Setup the class.
112      *
113      * @throws Exception exception
114      */
115     @BeforeClass
116     public static void setUpClass() throws Exception {
117
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");
122
123         DroolsPdpsElectionHandler.setIsUnitTesting(true);
124
125         saveTime = Whitebox.getInternalState(MonitorTime.class, MONITOR_FIELD_NAME);
126         saveFactory = Factory.getInstance();
127
128         resetInstanceObjects();
129
130         //Create the data access for xacml db
131         Properties stateManagementProperties = loadStateManagementProperties();
132
133         emfx = Persistence.createEntityManagerFactory("junitXacmlPU", stateManagementProperties);
134
135         // Create an entity manager to use the DB
136         emx = emfx.createEntityManager();
137
138         //Create the data access for drools db
139         Properties activeStandbyProperties = loadActiveStandbyProperties();
140
141         emfd = Persistence.createEntityManagerFactory("junitDroolsPU", activeStandbyProperties);
142
143         // Create an entity manager to use the DB
144         emd = emfd.createEntityManager();
145     }
146
147     /**
148      * Restores the system state.
149      *
150      * @throws IntegrityMonitorException if the integrity monitor cannot be shut down
151      */
152     @AfterClass
153     public static void tearDownClass() throws IntegrityMonitorException {
154         resetInstanceObjects();
155
156         Whitebox.setInternalState(MonitorTime.class, MONITOR_FIELD_NAME, saveTime);
157         Factory.setInstance(saveFactory);
158
159         DroolsPdpsElectionHandler.setIsUnitTesting(false);
160
161         emd.close();
162         emfd.close();
163
164         emx.close();
165         emfx.close();
166     }
167
168     /**
169      * Setup.
170      *
171      * @throws Exception exception
172      */
173     @Before
174     public void setUp() throws Exception {
175         resetInstanceObjects();
176
177         // set test time
178         testTime = new TestTimeMulti();
179         Whitebox.setInternalState(MonitorTime.class, MONITOR_FIELD_NAME, testTime);
180
181         Factory factory = mock(Factory.class);
182         when(factory.makeTimer()).thenAnswer(ans -> new PseudoTimer(testTime));
183         Factory.setInstance(factory);
184     }
185
186     private static void resetInstanceObjects() throws IntegrityMonitorException {
187         IntegrityMonitor.setUnitTesting(true);
188         IntegrityMonitor.deleteInstance();
189         IntegrityMonitor.setUnitTesting(false);
190
191         Whitebox.setInternalState(ActiveStandbyFeature.class, HANDLER_INSTANCE_FIELD, (Object) null);
192
193     }
194
195     /**
196      * Clean the xacml database.
197      */
198     public void cleanXacmlDb() {
199         et = emx.getTransaction();
200
201         et.begin();
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();
206         emx.flush();
207         et.commit();
208     }
209
210     /**
211      * Clean the drools database.
212      */
213     public void cleanDroolsDb() {
214         et = emd.getTransaction();
215
216         et.begin();
217         // Make sure we leave the DB clean
218         emd.createQuery("DELETE FROM DroolsPdpEntity").executeUpdate();
219         emd.flush();
220         et.commit();
221     }
222
223
224     // Tests hot standby when there is only one PDP.
225
226     //@Ignore
227     @Test
228     public void testAllSeemsWell() throws Exception {
229
230         logger.debug("\n\ntestAllSeemsWell: Entering\n\n");
231         cleanXacmlDb();
232         cleanDroolsDb();
233
234         Properties stateManagementProperties = loadStateManagementProperties();
235
236         logger.debug("testAllSeemsWell: Creating emfXacml");
237         final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory(
238                 "junitXacmlPU", stateManagementProperties);
239
240         Properties activeStandbyProperties = loadActiveStandbyProperties();
241         final String thisPdpId = activeStandbyProperties
242                 .getProperty(ActiveStandbyProperties.NODE_NAME);
243
244         logger.debug("testAllSeemsWell: Creating emfDrools");
245         EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory(
246                 "junitDroolsPU", activeStandbyProperties);
247
248         DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools);
249
250         logger.debug("testAllSeemsWell: Cleaning up tables");
251         conn.deleteAllPdps();
252
253         /*
254          * Insert this PDP as not designated.  Initial standby state will be
255          * either null or cold standby.   Demoting should transit state to
256          * hot standby.
257          */
258
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);
262         conn.insertPdp(pdp);
263         DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId);
264         logger.debug("testAllSeemsWell: After insertion, PDP={} has DESIGNATED={}",
265                 thisPdpId, droolsPdpEntity.isDesignated());
266         assertFalse(droolsPdpEntity.isDesignated());
267
268         logger.debug("testAllSeemsWell: Instantiating stateManagement object");
269         StateManagement sm = new StateManagement(emfXacml, "dummy");
270         sm.deleteAllStateManagementEntities();
271
272
273         // Now we want to create a StateManagementFeature and initialize it.  It will be
274         // discovered by the ActiveStandbyFeature when the election handler initializes.
275
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());
282             break;
283         }
284         assertNotNull(stateManagementFeatureApi);
285
286         final StateManagementFeatureApi smf = stateManagementFeatureApi;
287
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());
296             break;
297         }
298         assertNotNull(activeStandbyFeature);
299
300
301         logger.debug("testAllSeemsWell: Demoting PDP={}", thisPdpId);
302         // demoting should cause state to transit to hotstandby
303         smf.demote();
304
305
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);
309
310         // Verify that this formerly un-designated PDP in HOT_STANDBY is now designated and providing service.
311
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));
320
321         //Now we want to stall the election handler and see the if AllSeemsWell will make the
322         //standbystatus = coldstandby
323
324         DroolsPdpsElectionHandler.setIsStalled(true);
325
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);
330
331
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);
337
338         logger.debug("testAllSeemsWell: After isStalled=true, PDP= {} "
339                 + "has standbyStatus= {}", thisPdpId, smf.getStandbyStatus(thisPdpId));
340
341         assertTrue(smf.getStandbyStatus().equals(StateManagement.COLD_STANDBY));
342
343         //Now lets resume the election handler
344         DroolsPdpsElectionHandler.setIsStalled(false);
345
346         waitForCondition(() -> smf.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE),
347             RESUMED_ELECTION_HANDLER_SLEEP_TIME_SEC);
348
349         logger.debug("testAllSeemsWell: After isStalled=false, PDP= {} "
350                 + "has standbyStatus= {}", thisPdpId, smf.getStandbyStatus(thisPdpId));
351
352         assertTrue(smf.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE));
353
354         //resumedElectionHandlerSleepTime = 5000;
355         logger.debug("\n\ntestAllSeemsWell: Exiting\n\n");
356
357     }
358
359     private static Properties loadStateManagementProperties() throws IOException {
360         try (FileInputStream input = new FileInputStream(CONFIG_DIR + "/feature-state-management.properties")) {
361             Properties props = new Properties();
362             props.load(input);
363             return props;
364         }
365     }
366
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();
371             props.load(input);
372             return props;
373         }
374     }
375
376     private void waitForCondition(Callable<Boolean> testCondition, int timeoutInSeconds) throws InterruptedException {
377         testTime.waitUntil(testCondition);
378     }
379 }