dfc69304a4d2abf9da99d887d8d307e94883e5d8
[policy/drools-pdp.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * feature-active-standby-management
4  * ================================================================================
5  * Copyright (C) 2017-2018 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.controller.test;
22
23 import static org.junit.Assert.assertTrue;
24
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.util.Date;
28 import java.util.Properties;
29
30 import javax.persistence.EntityManager;
31 import javax.persistence.EntityManagerFactory;
32 import javax.persistence.EntityTransaction;
33 import javax.persistence.Persistence;
34
35 import org.apache.commons.lang3.time.DateUtils;
36 import org.junit.After;
37 import org.junit.AfterClass;
38 import org.junit.Before;
39 import org.junit.BeforeClass;
40 import org.junit.Test;
41 import org.onap.policy.common.im.StateManagement;
42 import org.onap.policy.drools.activestandby.ActiveStandbyFeatureAPI;
43 import org.onap.policy.drools.activestandby.ActiveStandbyProperties;
44 import org.onap.policy.drools.activestandby.DroolsPdpEntity;
45 import org.onap.policy.drools.activestandby.DroolsPdpImpl;
46 import org.onap.policy.drools.activestandby.DroolsPdpsConnector;
47 import org.onap.policy.drools.activestandby.DroolsPdpsElectionHandler;
48 import org.onap.policy.drools.activestandby.JpaDroolsPdpsConnector;
49 import org.onap.policy.drools.core.PolicySessionFeatureAPI;
50 import org.onap.policy.drools.statemanagement.StateManagementFeatureAPI;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /*
55  * Testing the allSeemsWell interface to verify that it correctly affects the 
56  * operational state.
57  */ 
58
59 public class AllSeemsWellTest {
60     private static final Logger  logger = LoggerFactory.getLogger(AllSeemsWellTest.class);
61     /*
62      * Currently, the DroolsPdpsElectionHandler.DesignationWaiter is invoked every 1 seconds, starting 
63      * at the start of the next multiple of pdpUpdateInterval, but with a minimum of 5 sec cushion
64      * to ensure that we wait for the DesignationWaiter to do its job, before 
65      * checking the results. Add a few seconds for safety
66      */ 
67
68     long sleepTime = 10000;
69
70     /*
71      * DroolsPdpsElectionHandler runs every 1 seconds, so it takes 10 seconds for the
72      * checkWaitTimer() method to time out and call allSeemsWell which then requires
73      * the forward progress counter to go stale which should add an additional 5 sec.
74      */
75
76     long stalledElectionHandlerSleepTime = 15000;
77
78     /*
79      * As soon as the election hander successfully runs, it will resume the forward progress.
80      * If the election handler runs ever 1 sec and test transaction is run every 1 sec and
81      * then fpc is written every 1 sec and then the fpc is checked every 2 sec, that could
82      * take a total of 5 sec to recognize the resumption of progress.  So, add 1 for safety.
83      */
84     long resumedElectionHandlerSleepTime = 6000;
85
86     private static EntityManagerFactory emfx;
87     private static EntityManagerFactory emfd;
88     private static EntityManager emx;
89     private static EntityManager emd;
90     private static EntityTransaction et;
91
92     private final String configDir = "src/test/resources/asw";
93
94     /*
95      * See the IntegrityMonitor.getJmxUrl() method for the rationale behind this jmx related processing.
96      */
97
98     /**
99      * Setup the class.
100      * 
101      * @throws Exception exception
102      */
103     @BeforeClass
104     public static void setUpClass() throws Exception {
105
106         String userDir = System.getProperty("user.dir");
107         logger.debug("setUpClass: userDir={}", userDir);
108         System.setProperty("com.sun.management.jmxremote.port", "9980");
109         System.setProperty("com.sun.management.jmxremote.authenticate","false");
110     }
111
112     @AfterClass
113     public static void tearDownClass() throws Exception {
114     }
115
116     /**
117      * Setup.
118      * 
119      * @throws Exception exception
120      */
121     @Before
122     public void setUp() throws Exception {
123         //Create teh data access for xaml db
124         Properties stateManagementProperties = new Properties();
125         stateManagementProperties.load(new FileInputStream(new File(
126                 configDir + "/feature-state-management.properties")));
127
128         emfx = Persistence.createEntityManagerFactory("junitXacmlPU", stateManagementProperties);
129
130         // Create an entity manager to use the DB
131         emx = emfx.createEntityManager();
132
133         //Create the data access for drools db
134         Properties activeStandbyProperties = new Properties();
135         activeStandbyProperties.load(new FileInputStream(new File(
136                 configDir + "/feature-active-standby-management.properties")));
137
138         emfd = Persistence.createEntityManagerFactory("junitDroolsPU", activeStandbyProperties);
139
140         // Create an entity manager to use the DB
141         emd = emfd.createEntityManager();
142
143         DroolsPdpsElectionHandler.setIsUnitTesting(true);
144     }
145
146     @After
147     public void tearDown() throws Exception {
148
149     }
150
151     /**
152      * Clean the xacml database.
153      */
154     public void cleanXacmlDb() {
155         et = emx.getTransaction();
156
157         et.begin();
158         // Make sure we leave the DB clean
159         emx.createQuery("DELETE FROM StateManagementEntity").executeUpdate();
160         emx.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate();
161         emx.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate();
162         emx.flush();
163         et.commit();
164     }
165
166     /**
167      * Clean the drools database.
168      */
169     public void cleanDroolsDb() {
170         et = emd.getTransaction();
171
172         et.begin();
173         // Make sure we leave the DB clean
174         emd.createQuery("DELETE FROM DroolsPdpEntity").executeUpdate();
175         emd.flush();
176         et.commit();
177     }
178
179
180     // Tests hot standby when there is only one PDP.
181
182     //@Ignore
183     @Test
184     public void testAllSeemsWell() throws Exception {
185
186         logger.debug("\n\ntestAllSeemsWell: Entering\n\n");
187         cleanXacmlDb();
188         cleanDroolsDb();
189
190         logger.debug("testAllSeemsWell: Reading stateManagementProperties");
191         Properties stateManagementProperties = new Properties();
192         stateManagementProperties.load(new FileInputStream(new File(
193                 configDir + "/feature-state-management.properties")));
194
195         logger.debug("testAllSeemsWell: Creating emfXacml");
196         final EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory(
197                 "junitXacmlPU", stateManagementProperties);
198
199         logger.debug("testAllSeemsWell: Reading activeStandbyProperties");
200         Properties activeStandbyProperties = new Properties();
201         activeStandbyProperties.load(new FileInputStream(new File(
202                 configDir + "/feature-active-standby-management.properties")));
203         final String thisPdpId = activeStandbyProperties
204                 .getProperty(ActiveStandbyProperties.NODE_NAME);
205
206         logger.debug("testAllSeemsWell: Creating emfDrools");
207         EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory(
208                 "junitDroolsPU", activeStandbyProperties);
209
210         DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools);
211
212         logger.debug("testAllSeemsWell: Cleaning up tables");
213         conn.deleteAllPdps();
214
215         /*
216          * Insert this PDP as not designated.  Initial standby state will be 
217          * either null or cold standby.   Demoting should transit state to
218          * hot standby.
219          */
220
221         logger.debug("testAllSeemsWell: Inserting PDP={} as not designated", thisPdpId);
222         Date yesterday = DateUtils.addDays(new Date(), -1);
223         DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday);
224         conn.insertPdp(pdp);
225         DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId);
226         logger.debug("testAllSeemsWell: After insertion, PDP={} has DESIGNATED={}",
227                 thisPdpId, droolsPdpEntity.isDesignated());
228         assertTrue(droolsPdpEntity.isDesignated() == false);
229
230         logger.debug("testAllSeemsWell: Instantiating stateManagement object");
231         StateManagement sm = new StateManagement(emfXacml, "dummy");
232         sm.deleteAllStateManagementEntities();
233
234
235         // Now we want to create a StateManagementFeature and initialize it.  It will be
236         // discovered by the ActiveStandbyFeature when the election handler initializes.
237
238         StateManagementFeatureAPI smf = null;
239         for (StateManagementFeatureAPI feature : StateManagementFeatureAPI.impl.getList()) {
240             ((PolicySessionFeatureAPI) feature).globalInit(null, configDir);
241             smf = feature;
242             logger.debug("testAllSeemsWell stateManagementFeature.getResourceName(): {}", smf.getResourceName());
243             break;
244         }
245         if (smf == null) {
246             logger.error("testAllSeemsWell failed to initialize.  "
247                     + "Unable to get instance of StateManagementFeatureAPI "
248                     + "with resourceID: {}", thisPdpId);
249             logger.debug("testAllSeemsWell failed to initialize.  "
250                     + "Unable to get instance of StateManagementFeatureAPI "
251                     + "with resourceID: {}", thisPdpId);
252         }
253
254         // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature
255         // that has been created.
256         ActiveStandbyFeatureAPI activeStandbyFeature = null;
257         for (ActiveStandbyFeatureAPI feature : ActiveStandbyFeatureAPI.impl.getList()) {
258             ((PolicySessionFeatureAPI) feature).globalInit(null, configDir);
259             activeStandbyFeature = feature;
260             logger.debug("testAllSeemsWell activeStandbyFeature.getResourceName(): {}", 
261                     activeStandbyFeature.getResourceName());
262             break;
263         }
264         if (activeStandbyFeature == null) {
265             logger.error("testAllSeemsWell failed to initialize.  "
266                     + "Unable to get instance of ActiveStandbyFeatureAPI "
267                     + "with resourceID: {}", thisPdpId);
268             logger.debug("testAllSeemsWell failed to initialize.  "
269                     + "Unable to get instance of ActiveStandbyFeatureAPI "
270                     + "with resourceID: {}", thisPdpId);
271         }
272
273
274         logger.debug("testAllSeemsWell: Demoting PDP={}", thisPdpId);
275         // demoting should cause state to transit to hotstandby
276         smf.demote();
277
278
279         logger.debug("testAllSeemsWell: Sleeping {} ms, to allow JpaDroolsPdpsConnector "
280                 + "time to check droolspdpentity table", sleepTime);
281         sleep(sleepTime);
282
283
284         // Verify that this formerly un-designated PDP in HOT_STANDBY is now designated and providing service.
285
286         droolsPdpEntity = conn.getPdp(thisPdpId);
287         logger.debug("testAllSeemsWell: After sm.demote() invoked, DESIGNATED= {} "
288                 + "for PDP= {}", droolsPdpEntity.isDesignated(), thisPdpId);
289         assertTrue(droolsPdpEntity.isDesignated() == true);
290         String standbyStatus = smf.getStandbyStatus(thisPdpId);
291         logger.debug("testAllSeemsWell: After demotion, PDP= {} "
292                 + "has standbyStatus= {}", thisPdpId, standbyStatus);
293         assertTrue(standbyStatus != null  &&  standbyStatus.equals(StateManagement.PROVIDING_SERVICE));
294
295         //Now we want to stall the election handler and see the if AllSeemsWell will make the
296         //standbystatus = coldstandby
297
298         DroolsPdpsElectionHandler.setIsStalled(true);
299
300         logger.debug("testAllSeemsWell: Sleeping {} ms, to allow checkWaitTimer to recognize "
301                 + "the election handler has stalled and for the testTransaction to fail to "
302                 + "increment forward progress and for the lack of forward progress to be recognized.",
303                 stalledElectionHandlerSleepTime);
304
305
306         //It takes 10x the update interval (1 sec) before the watcher will declare the election handler dead
307         //and that just stops forward progress counter.  So, the fp monitor must then run to determine
308         //if the fpc has stalled.  That will take about another 5 sec.
309         sleep(stalledElectionHandlerSleepTime);
310
311         logger.debug("testAllSeemsWell: After isStalled=true, PDP= {} "
312                 + "has standbyStatus= {}", thisPdpId, smf.getStandbyStatus(thisPdpId));
313
314         assertTrue(smf.getStandbyStatus().equals(StateManagement.COLD_STANDBY));
315
316         //Now lets resume the election handler
317         DroolsPdpsElectionHandler.setIsStalled(false);
318
319         sleep(resumedElectionHandlerSleepTime);
320
321         logger.debug("testAllSeemsWell: After isStalled=false, PDP= {} "
322                 + "has standbyStatus= {}", thisPdpId, smf.getStandbyStatus(thisPdpId));
323
324         assertTrue(smf.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE));
325
326         //resumedElectionHandlerSleepTime = 5000;
327         logger.debug("\n\ntestAllSeemsWell: Exiting\n\n");
328
329     }
330
331     private void sleep(long sleepms) throws InterruptedException {
332         Thread.sleep(sleepms);
333     }
334 }